美文网首页
191. Number of 1 Bits

191. Number of 1 Bits

作者: 7ccc099f4608 | 来源:发表于2020-03-23 13:17 被阅读0次

    https://leetcode-cn.com/problems/number-of-1-bits/

    image.png

    (图片来源https://leetcode-cn.com/problems/number-of-1-bits/

    日期 是否一次通过 comment
    2020-03-23 0

    public int hammingWeight(int n) {
            int res = 0;
            while(n != 0) {  // 不是n >= 0, 而是 n != 0
                if((n&1) == 1) {
                    res ++;
                }
    
    //            n >>= 1;  // >> 右移,如果使用,则符号位也会被移动。如果输入为-3,每次右移高位都会补1(负数),导致死循环
                n >>>= 1;   // >>> 无符号右移
    
            }
    
            return res;
        }

    相关文章

      网友评论

          本文标题:191. Number of 1 Bits

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