338. Counting Bits

来源:互联网 发布:知乎 江南七怪的实力 编辑:程序博客网 时间:2024/05/23 18:11

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.

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.Show More Hint 

Credits:

Special thanks to @ syedee for adding this problem and creating all test cases.


求0~num的数,每个数的二进制表示中分别有多少个1。

已经给提示了,2的幂次数1的个数只有1个,每次找出当前的数和哪个2的幂次最接近,把这个作为基数(其实就是1),

然后当前搜索数=(当前数-离当前数最近的2的幂次),这个当前搜索数一定在前面求出来了,直接加上就好。

 public static int[] countBits(int num){int[] arr=new int[num+1];if(num<2){for(int i=0;i<=num;i++)arr[i]=i;return arr;}arr[0]=0;arr[1]=1;arr[2]=1;double lg2=Math.log10(2);for(int i=3;i<=num;i++){int power=(int) (Math.log10(i)/lg2);int base=(int) Math.pow(2, power);arr[i]=arr[base]+(i-base==0?1:arr[i-base]);}return arr;}


0 0
原创粉丝点击