题目:https://leetcode-cn.com/problems/number-of-1-bits/
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>>= 1;
//>>>表示无符号的右移:按照二进制把数字右移指定数位,高位直接补零,低位移除
//任何数字跟掩码1进行逻辑与运算,都可以获得这个数字都最低位
}
return count;
}
}

本文详细解析了LeetCode上的一道经典位操作题目,通过一个Java实现的例子,介绍了如何计算一个整数中1的个数。使用了位运算符进行高效计算,包括无符号右移操作和逻辑与运算。
267

被折叠的 条评论
为什么被折叠?



