leetcode 191. 位1的个数(移位操作)

题目

在这里插入图片描述

题解

这个题,可以直接参考 190. 颠倒二进制位

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int cnt = 0;
        for (int i = 0; i < 32; i++) {
            cnt += n >>> i & 1;
            System.out.println(n >>> i & 1);  // 无符号右移
        }
        return cnt;
    }
}

在这里插入图片描述

评论区一些比较好的解法

Java API

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        return Integer.bitCount(n);
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_42483341/article/details/107519935
今日推荐