[LeetCode] Counting Bits

338. Counting Bits

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1’s in the binary representation of i.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
vector<int> countBits(int n) {
if(n == 0) return {0};
vector<int> res {0,1};
for(int i = 2,counter = 2; i <= n; i++) {
if(i == counter * 2) counter *= 2;
res.push_back(1 + res[i - counter]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/01/PS/LeetCode/counting-bits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.