美文网首页Leetcode
Leetcode.191.Number of 1 Bits

Leetcode.191.Number of 1 Bits

作者: Jimmy木 | 来源:发表于2019-11-18 13:48 被阅读0次

    题目

    给定一个无符号整数, 求出其中二进制数中有多个1.

    Input: 11(00000000000000000000000000001011)
    Output: 3
    

    思路

    采用&运算, 当(x&(1<<i)) == (1<<i)说明x的第i位为1.

    int hammingWeight(uint32_t n) {
        int res = 0;
        int i = 0;
        while (n > 0) {
            int x = 1 << i++;
            if ((n & x) == x) {
                n -= x;
                res++;
            }
        }
        return res;
    }
    

    总结

    巧妙使用位运算, 掌握位运算的使用场景.

    相关文章

      网友评论

        本文标题:Leetcode.191.Number of 1 Bits

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