剑指 Offer 15. 二进制中1的个数

原题链接

分析

因为我们知道使用位运算符进行计算的时候就是使用的二进制位,所以可以直接行移位操作,然后判定有多少个1

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

也可以换一种写法

我们知道n & (n - 1),就相当于找到了n中的最低位的1然后变成了0,所以只需要找到最后位的1对应位置改变即可。

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

        return res;
    }
}
posted @ 2021-04-29 13:40  Lngstart  阅读(39)  评论(0编辑  收藏  举报