二进制中1的个数

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

演示:

5:0101

n=5;

n&1;n>>>=1的模拟

n      &     1

0101&0001=0001

0010&0001=0000

0001&0001=0001

0000

有几个1,向右移位时与1相与会保留1,所以res就是1的个数

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>>>=1;//无符号右移一位
    }
    return res;
    
    }
}
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        //位运算
        int res = 0,i = 0;
        while(i<32){
            res+=(n>>>i)&1;
            //System.out.println(res);
            i++;
        }
        return res;
    }
}

不一样的烟火
原文地址:https://www.cnblogs.com/cstdio1/p/11248534.html