338. Counting Bits
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.
题目含义:统计二进制数字num以内每个数中‘1’的个数
1 2 int countbit(int i) 3 { 4 //无关trick i&(i - 1), 这个本来是用来判断一个数是否是2的指数的快捷方法,比如8,二进制位1000, 那么8&(8-1)为0,只要为0就是2的指数 5 // 按照定义做, x&(x-1)可以消去最右边的1 6 int count = 0; 7 while(i>0) 8 { 9 i &= (i-1); 10 count ++; 11 } 12 return count; 13 } 14 15 public int[] countBits(int num) { 16 int[] res = new int[num+1]; 17 if (num == 0) return res; 18 res[0] = 0; 19 for (int i=1;i<=num;i++) 20 { 21 // res[i] = countbit(i);//解法一 22 res[i] = res[i & (i - 1)] + 1;//每个i值都是i&(i-1)对应的值加1 23 } 24 return res; 25 }