1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { private: int countOnes(int n) { int ones = 0; while (n) { n &= (n - 1); ++ones; } return ones; } public: vector<int> countBits(int num) { vector<int> ans(num + 1); for (int i = 0; i <= num; ++i) ans[i] = countOnes(i); return ans; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public: vector<int> countBits(int num) { vector<int> dp(num + 1); int highBit = 0; for (int i = 1; i <= num; ++i) { if ((i & (i - 1)) == 0) highBit = i; dp[i] = dp[i - highBit] + 1; } return dp; } };
|
1 2 3 4 5 6 7 8 9
| class Solution { public: vector<int> countBits(int num) { vector<int> dp(num + 1); for (int i = 1; i <= num; ++i) dp[i] = dp[i >> 1] + (i & 1); return dp; } };
|
1 2 3 4 5 6 7 8 9
| class Solution { public: vector<int> countBits(int num) { vector<int> dp(num + 1); for (int i = 1; i <= num; ++i) dp[i] = dp[i & (i - 1)] + 1; return dp; } };
|
Reference: 比特位计数 - 比特位计数 - 力扣(LeetCode)