问题:
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:
Fornum = 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.
解决:
【题意】给定n,然后计算从0到n之间所有的数的bit为1的个数。
【注】之前有的hint,后来被删了。
Hint:
- You should make use of what you have produced already.
- Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
- Or does the odd/even status of the number help you in calculating the number of 1s?
① 直接解决。时间复杂度O(n*sizeof(integer))。
class Solution {//4ms
public int[] countBits(int num) { int[] res = new int[num + 1]; for (int i = 0;i <= num;i ++){ if (i == 0){ res[i] = 0; }else{ int count = 1; int tmp = i; while((tmp & (tmp - 1)) != 0){ count ++; tmp = (tmp & (tmp - 1)); } res[i] = count; } } return res; } }② 对于数字2(10), 4(100), 8(1000), 16(10000), ...,其二进制表示中只有1个1。其他任意数字都可以表示为2^m + x。例如9=8+1, 10=8+2。其他任意数字中1的个数是1 + x中1的个数。时间复杂度O(n)
class Solution { //3ms
public int[] countBits(int num) { int[] res = new int[num + 1]; int p = 1;//p指向x的下标 int pow = 1;//指向2的幂 for (int i = 1;i <= num;i ++){ if (i == pow){ res[i] = 1; pow <<= 1; p = 1; }else{ res[i] = res[p] + 1; p ++; } } return res; } }③
class Solution {//2ms
public int[] countBits(int num) { int[] res = new int[num + 1]; for (int i = 1;i <= num;i ++){ res[i] = res[i & (i - 1)] + 1; } return res; } }