标签:
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:
Solution:
动态规划,如果i是奇数,f[i] = f[i/2] + 1, 偶数, f[i] = f[i/2]
1 vector<int> countBits(int num) 2 { 3 vector<int> table(num + 1, 0); 4 5 for (int i = 1; i <= num; i++) 6 if (i & 1) 7 table[i] = table[i >> 1] + 1; 8 else 9 table[i] = table[i >> 1]; 10 11 return table; 12 }
标签:
原文地址:http://www.cnblogs.com/ym65536/p/5601880.html