zoukankan      html  css  js  c++  java
  • [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).

    Analysis:  Denote f(n) as the answer of number n. 

    to get numbers of n bits from n - 1 bits,  we add a prefix 0 or 1 to all n - 1 bits numbers.  Adding a prefix 0 has no impact on consecutive 0s, so the total number of non-consecutive 1s in all n bits with a leading 0 prefix is just f(n - 1); Adding a prefix 1 forces the 2nd MSB be 0. With the leading two bits fixed as 10, the total number of non-consecutive 1s in all n bits with a leading 1 prefix is just 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 }
  • 相关阅读:
    016_异步处理_Future
    013_REST Service
    012_介绍Soap&Rest
    011_Validation Rule about Time
    010_Soap update
    006_Salesforce Sharing 使用说明
    005_重写 Standard Delete Button
    004_Intelij 使用,Anonymous Apex
    003_关于IntellJ IDE 2016 1. 4的使用
    Dashborad 上显示出错
  • 原文地址:https://www.cnblogs.com/lz87/p/7288711.html
Copyright © 2011-2022 走看看