Counting Bits -leetcode

introduction:

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
 class Solution {
public
: vector<int> countBits(int num) { vector<int> result; if(num>=0) // 1. not num==0 result.push_back(0); if(num>=1) // 1. not num==1 result.push_back(1); for (int i=2;i<=num;i++) { int k = (log(i)/log(2)); if(i>=pow(2,k) && i<pow(2,k)+pow(2,k-1)) // 2. use pow (in math.h) result.push_back(result.at(i-pow(2,k-1))); else if(i>=pow(2,k)+pow(2,k-1) && i<pow(2,k+1)) // 3. >= or >
result.push_back(result.at(i-pow(2,k-1))+1);
}
 result; 
  }
};

解题思路:从 1 到15 ,它的1的个数可以在二叉树中看出(从左到右,从上到下,15=b1111为最后一个对应4)。

而且 满足 : 第k+1层的前半部分 是第k层的复制 , 后半部分是第k层所有元素加1 

                                       

debug:

  1、 如果 是 ==0 或者  ==1 作为判断,当>1 时,将会缺少0和1的pushback

  2、 幂运算  result=pow(x,y);   

  3、 注意判断语句的边界条件

注: 本文原创,转载请说明出处

    原文地址:https://www.cnblogs.com/NeilZhang/p/5340777.html