338. Counting Bits

来源:互联网 发布:恶搞老鼠软件 编辑:程序博客网 时间:2024/06/05 07:25

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 timeO(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.

计算0 ≤ i ≤ num内所有数字二进制的“1“”的个数


i   二进制 个数 i&(i-1)

0  0000    0      0000

1  0001    1      0000

2  0010    1      0000

3  0011    2      0010

4  0100    1      0000

5  0101    2      0100

6  0110    2      0100

7  0111    3      0110

8  1000    1      0000

9  1001    2      1000

10  1010   2     1000

11  1011   3      1010

12  1100   2      1000

13  1101   3      1100

14  1110   3      1100

15  1111   4       1110


public static int[] countBits(int num) {int[] res = new int[num + 1];res[0] = 0;for(int i = 1;i <= num;i++){res[i] = res[i & (i - 1)] + 1;}return res;}


0 0
原创粉丝点击