二进制中1的个数--与运算

题目描述

在这里插入图片描述

代码

public class Solution {
    
    
    // you need to treat n as an unsigned value

    /*
        & 与运算:0&0=0   1&0=0   0&1=0   1&1=1
		| 或运算:有1则1
		^ 异或:   同则0,不同则1
    */
    public int hammingWeight(int n) {
    
    
       
        int res = 0;
        while(n != 0){
    
    
            res = res + (n & 1); //最右一位
            n = n >>> 1;         //无符号右移一位,,Java 中无符号右移为 ">>>"
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44809329/article/details/113914596
今日推荐