题目地址:
https://www.lintcode.com/problem/counting-bits/description
给定 n n n,求 0 ∼ n 0\sim n 0∼n的每个数的二进制表示中 1 1 1的个数。
思路是动态规划。令 f [ i ] f[i] f[i]是 i i i的二进制表示中 1 1 1的个数。则: f [ i ] = f [ i > > 1 ] + ( i & 1 ) = f [ i / 2 ] + ( i % 2 ) f[i]=f[i>>1]+(i\&1)=f[i/2]+(i\%2) f[i]=f[i>>1]+(i&1)=f[i/2]+(i%2)代码如下:
public class Solution {
/**
* @param num: a non negative integer number
* @return: an array represent the number of 1's in their binary
*/
public int[] countBits(int num) {
// write your code here
int[] res = new int[num + 1];
res[0] = 0;
for (int i = 1; i <= num; i++) {
res[i] = res[i >> 1] + (i & 1);
}
return res;
}
}
时空复杂度 O ( n ) O(n) O(n)。