LeetCode--No.191--Number of 1 Bits--哎有点地方想不通

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

方法一:

将n与n-1进行与运算。则可消除掉最右面的一个1,其余不变。
所以,需要计算几次后,得到n=0,则n中有几个1.

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        while(n>0){
            n = n & (n-1);
            count++;
        }
        return count;
    }
思路是很好的。计算次数真的很小
但是有问题。会报错。

2147483648, 转化为二进制位 1000,0000,0000,0000,0000,0000,0000,0000(总共32位,后11位均为0)
所以应该输出1. 但是这种方法输出为0.

而int型,最大为2147483647.

至于为什么输出0,我也不知道。。。谁能告诉我?

方法二:

这个方法的思路是:将一个1,放在每一位上试一下,如果和n求与之后,结果为0,那么这一位上的bite肯定是0,否则是1.
所以数一下不为0的个数即可。

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        for(int i = 0; i < 32; i++){
            if (getBit(n,i) == true){
                count++;
            }
        }
        return count;
    }
    public boolean getBit(int n, int i){
        return (n & (1 << i)) != 0;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值