每天Leetcode 刷题 初级算法篇-位1的个数

题目要求:

在这里插入图片描述

力扣题解:循环和位移动

在这里插入图片描述

代码

/**
 * @program: mydemo
 * @description: 位1的个数
 * @author: Mr.zeng
 * @create: 2021-02-25 09:44
 **/
public class Solution36 {
    
    
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
    
    
        int bits=0;
        int mask=1;
        for (int i = 0; i < 32; i++) {
    
    
            if((n&mask)!=0){
    
    
                bits++;
            }
            mask<<=1;
        }
        return bits;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42292697/article/details/114062097