二进制中1的个数
描述
简单
请实现一个函数,输入一个整数(以二进制串形式),输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:
输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
提示:
- 输入必须是长度为 32 的 二进制串 。
解题
trick
# python
class Solution:
def hammingWeight(self, n: int) -> int:
return bin(n).count('1')
// java
public class Solution {
public int hammingWeight(int n) {
return Integer.bitCount(n);
}
}
位操作
# python
class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
while n:
res += n & 1
n >>= 1
return res
// java
// 有符号的数右移需要 >>>
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0){
res += n & 1;
n >>>= 1;
}
return res;
}
}
假设:
n =
- 1 0 1 0 1 0
则 n - 1 =
- 1 0 1 0 0 1
然后 n & (n - 1) =
- 1 0 1 0 0 0
那么n &= n - 1
可以理解为消去n最右边的1
# python
class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
while n:
res += 1
n &= n - 1
return res
// java
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res++;
n &= n - 1;
}
return res;
}
}