sword_for_offer/docs/剑指 Offer 15. 二进制中 1 的个数.md
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;
}
};
{:width=400}
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;
}
};