题源:leetcode
链接:https://leetcode-cn.com/problems/counting-bits/
这里还是使用动态规划去做,考虑到每隔2^n,结果加一,则可用动态规划。
1 class Solution { 2 public: 3 vector<int> countBits(int n) { 4 vector<int> bits(n + 1); 5 int highBit = 0; 6 for (int i = 1; i <= n; i++) { 7 if ((i & (i - 1)) == 0) { 8 highBit = i; 9 } 10 bits[i] = bits[i - highBit] + 1; 11 } 12 return bits; 13 } 14 }; 15 16 17 // 0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
其中第七行的i-1&i ==0 是用来判断是否为2的幂