1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Solution { public: #if 1 vector<int> countBits(int n) { vector<int> ans(n + 1); ans[0] = 0; int leadingOne = 1; for (int i = 1; i <= n; i++) { if ((leadingOne << 1) == i) leadingOne <<= 1; ans[i] = ans[i - leadingOne] + 1; } return ans; } #else vector<int> countBits(int n) { vector<int> ans(n + 1); for (int i = 0; i <= n; i++) ans[i] = __builtin_popcount(i); return ans; } #endif }; |