你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。
2. 解法-位运算
Java
class Solution {
public int[] countBits(int num) {
int[] ans = new int[num+1];
ans[0] = 0;
for (int i=1;i<=num;i++) {
ans[i] = count(i);
}
return ans;
}
public int count(int n) {
int cnt = 0;
while (n!=0) {
n = n & (n-1);
cnt++;
}
return cnt;
}
}