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]
.
本题要求返回num内的每个数字二进制表示有多少个1,统计并返回一个数组。
我们定一个result数组其中result【i】 = result[i>>1]+(i&1);
最后返回数组即可。
代码如下:
class Solution {
public int[] countBits(int num) {
int[] result = new int[num+1];
for (int i = 0; i < result.length; i++) {
result[i] = result[i>>1]+(i&1);
}
return result;
}
}