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

LeetCode 191. Number of 1 Bits

作者: _Zy | 来源:发表于2018-11-13 16:55 被阅读8次

    Leetcode : Number of 1 Bits
    Diffculty:Easy

    要求写一个函数,函数接收一个无符号数字后,返回该数字中1的个数。(这个问题也被叫做 Hamming Weight)

    例如:
    Input : 11(00000000000000000000000000001011)
    Output : 3(里面有3个1)

    思路:
    该问题是典型的位操作算法题。
    因为 数字 1 的二进制数最后一位是1,前面所有位都是0。和数字 n 进行&运算的结果,可以判断数字n的最右位是1还是0。
    然后逐个将数字 n 右移,一直到n全部移完。

    下面是代码:

    public static int hammingWeight(int n) {
            int num = 0;
            while(n != 0){    // 如果数字n==0则直接结束
                num += n&1;   // 将n&1 的结果直接加到num上,累积遇到1的个数
                n >>>=1;      // 将n无符号右移1位
            }
            return num;
        }
    

    LeetCode 执行结果:1ms - beats 98.42%

    相关文章

      网友评论

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

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