Description:
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 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [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]内所有整数得二进制表示中1的个数;
解法:要求时间复杂度为O(n),空间复杂度也为O(n);我们可以利用动态规划的思想,如果当前需要计算的元素是num,通常的做法是计算处num的二进制表示后统计1的个数,当我们遍历到num时,说明元素num/2二进制表示中1的个数已经计算过了,我们现在只需要计算考虑
- num % 2 == 1 ,结果为元素num/2的二进制表示中1的个数 + 1
- num % 2 == 0, 结果为元素num/2的二进制表示中1的个数
Java
class Solution {
public int[] countBits(int num) {
int[] result = new int[num + 1];
result[0] = 0;
for (int i = 1; i <= num; i++) {
result[i] = i % 2 == 1 ? result[i/2] + 1 : result[i/2];
}
return result;
}
}