*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;
}
};
有意思的题。我的做法,把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;
}
};
相关文章推荐
- LeetCode338. Counting Bits还有更好的解法吗
- 【LeetCode】338. Counting Bits
- 【leetcode】【Medium】【338. Counting Bits】【规律】
- LeetCode笔记:338. Counting Bits
- LeetCode - 338. Counting Bits
- LeetCode 338. Counting Bits(计算二进制数中1的位数)
- LeetCode338. Counting Bits
- leetCode 338. Counting Bits | Dynamic Programming | Medium
- LeetCode-338. Counting Bits
- LeetCode 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCode 338. Counting Bits
- LeetCode338. Counting Bits题解
- leetcode-338. Counting Bits 统计十进制数字的二进制表示中1的个数,列表的定义,奇偶判断
- 【leetcode】338. Counting Bits
- Leetcode 338. Counting Bits
- leetcode - 338. Counting Bits (bit mannipulation)
- Leetcode 338. Counting Bits
- 【leetcode】338. Counting Bits
- 【LeetCode】338. Counting Bits