给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组ans 作为答案。
class Solution {
public:
vector<int> countBits(int n) {
//题目要求长度为 n + 1 的数组 ans
vector<int> ans(n + 1);
//设置初始值,已知0的二进制1的个数为0
ans[0] = 0;
//遍历各个整数
//其实ans[i] = ans[i >>= 1] + ans末尾二进制是不是1
for(int i = 1; i <= n; i++){
int temp = i;
//i是奇数,那么末尾一定是1
if(i % 2 == 1)
++ans[i];
temp >>= 1;
//temp已经计算好了,可以直接相加
ans[i] += ans[temp];
}
return ans;
}
};
Accepted
15/15 cases passed (4 ms)
Your runtime beats 85.02 % of cpp submissions
Your memory usage beats 80.44 % of cpp submissions (7.6 MB)