*LeetCode-Number of 1 Bits

本文介绍了一种计算整数二进制表示中1的个数(即汉明重量)的方法。通过将整数的最低位与1进行按位与操作,并利用Java中的无符号右移操作来迭代处理每一位,直到整数变为0。特别注意对于Java中的整数类型为带符号类型,因此使用不考虑符号位的右移操作非常重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每次把n的最后一位和1做& 假如是1 那么就累计有一位,

然后把n右移一位 注意这里右移用的是unsigned >>> 因为不要考虑最高位的sign 

然后while的判断条件一定是 n != 0

In Java we need to put attention on the fact that the maximum integer is 2147483647. Integer type in Java is signed and there is no unsigned int. So the input 2147483648 is represented in Java as -2147483648 (in java int type has a cyclic representation, that means Integer.MAXVALUE+1==Integer.MINVALUE). This force us to use 

n!=0

in the while condition and we cannot use 

n>0

because the input 2147483648 would correspond to -2147483648 in java and the code would not enter the while if the condition is n>0 for n=2147483648.


public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int res = 0;
        while ( n != 0 ){
            res += ( n & 1 );
            n = n >>> 1;
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值