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:
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?
Hide Similar Problems
public classSolution {public int[] countBits(intnum) {int[] ret = new int[num+1];//f(i) = f(i/2) + i%2.
for(int i = 1; i<=num; ++i)
ret[i]= ret[i/2]+i%2;returnret;
}
}
191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1‘ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11‘ has binary representation 00000000000000000000000000001011, so the function should return 3.
The signed right shift operator ">>" shifts a bit pattern to the right.
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
e.g.
System.out.println(-1 >> 1); //-1
System.out.println(-1 >> 31); //-1
System.out.println(-1 >>> 29); //7
System.out.println(-1 >>> 30); //3
System.out.println(-1 >>> 31); //1
System.out.println(-1 >>> 32); //-1, <=> -1 >>> 0
System.out.println(-1 >>> 33); //2147483647, <=> -1 >>> 1
int n = -15;
System.out.println(Integer.toBinaryString(n));//11111111111111111111111111110001
int m = n >> 1;
System.out.println(m);//-8
System.out.println(n / 2);//-7
System.out.println(Integer.toBinaryString(m));//11111111111111111111111111111000
Bit Operators:
http://stackoverflow.com/questions/15457893/java-right-shift-on-negative-number
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
public classSolution {//you need to treat n as an unsigned value
public int hammingWeight(intn) {int sum = 0;while(n!=0)
{
sum+= n&1;
n= n >>> 1;
}returnsum;
}
}
原文:http://www.cnblogs.com/neweracoding/p/5629592.html