文章目录
338. 比特位计数
暴力算法
java
class Solution {
private int count(int n) {
int res = 0;
if (n == 0) {
return 0;
}
for (int i = 0; i < 32; i++) {
res += ((n >> i) & 1);
}
return res;
}
public int[] countBits(int n) {
int[] ans = new int[n+1];
for (int i = 0; i <= n; i++) {
ans[i] = count(i);
}
return ans;
}
}
存储已经计算的值
java
class Solution {
public int[] countBits(int n) {
int[] ans = new int[n+1];
for (int i = 0; i <= n; i++) {
ans[i] = ans[i >> 1] + (i & 1);
}
return ans;
}
}