leetcode 191 Number of 1 Bits C++

来源:互联网 发布:约瑟夫问题 c语言 编辑:程序博客网 时间:2024/06/06 21:43

这个一分钟搞定。

就是要对位运算有一定的了解

乘2相当于整体二进制位左移一位,而且这种运算方式比直接乘要快。

因此只要判断是奇数就加一,然后整体右移一位。


class Solution {public:    int hammingWeight(uint32_t n) {        int count = 0;        while(n){            if (n % 2 == 1) count++;            n = n>>1;        }        return count;    }};

刚看到了一种更快的方式,直接与操作。

class Solution {public:    int hammingWeight(uint32_t n)    {        int res = 0;        while(n)        {            n &= n - 1;            ++ res;        }        return res;    }};


0 0
原创粉丝点击