美文网首页
LeetCode 338-Counting Bits

LeetCode 338-Counting Bits

作者: 胡哈哈哈 | 来源:发表于2016-06-03 23:42 被阅读35次

分析

给每个数循环做x & (x - 1)并计数就是它二进制数中1的个数。

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> ret;
        for (int i = 0; i <= num; ++i) {
            ret.push_back(count(i));
        }
        return ret;
    }
    
    int count(int x) {
        int ret = 0;
        while (x) {
            x = x & (x - 1);
            ++ret;
        }
        return ret;
    }
};

相关文章

网友评论

      本文标题:LeetCode 338-Counting Bits

      本文链接:https://www.haomeiwen.com/subject/widldttx.html