[Coding Made Simple] Number without consecutive 1s in binary representation

Posted Push your limit!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Coding Made Simple] Number without consecutive 1s in binary representation相关的知识,希望对你有一定的参考价值。

Given a number n, find the total number of numbers from 0 to 2^n - 1 which do not have consecutive 1s in their binary representation.

 

Solution.  This problem is the equivalence of fibonacci sequence. For a given n, f(n) = f(n - 1) + f(n - 2).

 

 1 public int getTotalNumberOfNoConsecutiveOnes(int n) {
 2     if(n == 0) {
 3         return 1;
 4     }
 5     if(n == 1) {
 6         return 2;
 7     }
 8     int[] T = new int[n + 1];
 9     T[0] = 1;
10     T[1] = 2;
11     for(int i = 2; i <= n; i++) {
12         T[i] = T[i - 1] + T[i - 2];
13     }
14     return T[n];
15 }

 

以上是关于[Coding Made Simple] Number without consecutive 1s in binary representation的主要内容,如果未能解决你的问题,请参考以下文章

[Coding Made Simple] Longest Increasing Subsequence

[Coding Made Simple] String Interleaving

[Coding Made Simple] Matrix Chain Multiplication

[Coding Made Simple] Burst Balloon

[Coding Made Simple] Subset Sum Problem

[Coding Made Simple] Minimum Cost Path