您的位置:首页 > 其它

*Leetcode 338. Counting Bits

2018-03-05 20:22 411 查看
https://leetcode.com/problems/counting-bits/description/

有意思的题。我的做法,把i分奇偶数

class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans;
ans.push_back(0);
if (num == 0) return ans;
ans.push_back(1);
if (num == 1) return ans;
int dp[num+1];
dp[0] = 0;
dp[1] = 1;

for (int i = 2; i <= num; i++) {
if (i%2) {
dp[i] = dp[i/2] + 1;
} else {
dp[i] = dp[i/2];
}
ans.push_back( dp[i] );
}
return ans;
}
};看了discuss,有一个比较tricky的东西 https://leetcode.com/problems/counting-bits/discuss/79527/Four-lines-C++-time-O(n)-space-O(n)
i&(i-1) drops the lowest set bit. For example: i = 14, its binary representation is 1110, so i-1 is 1101, i&(i-1) = 1100, the number of “1” in its binary representation decrease one, so ret[i] = ret[i&(i-1)] + 1. (Sorry, my English is so poor and I have tried my best to make it clearly, I hope you can understand my explanation)
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for (int i = 1; i <= num; ++i)
ret[i] = ret[i&(i-1)] + 1;
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: