leetbook_ioa/docs/LCR 133. 位 1 的个数.md
根据 与运算 定义,设二进制数字 $n$ ,则有:
根据以上特点,考虑以下 循环判断 :
res += n & 1 : 若 $n & 1 = 1$ ,则统计数 $res$ 加一。n >>= 1 : 将二进制数字 $n$ 无符号右移一位( Java 中无符号右移为 "$>>>$" ) 。<,,,,,,,,>
class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
while n:
res += n & 1
n >>= 1
return res
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
}
class Solution {
public:
int hammingWeight(uint32_t n) {
unsigned int res = 0; // c++ 使用无符号数
while(n != 0) {
res += n & 1;
n >>= 1;
}
return res;
}
};
{:align=center width=450}
res += 1 : 统计变量加 $1$ ;n &= n - 1 : 消去数字 $n$ 最右边的 $1$ 。<,,,>
class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
while n:
res += 1
n &= n - 1
return res
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res++;
n &= n - 1;
}
return res;
}
}
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while(n != 0) {
res++;
n &= n - 1;
}
return res;
}
};