要计算一个整数的二进制表示中1的个数,可以使用位运算实现高效计算。以下是具体方法和示例:
一、核心方法:位运算技巧
与运算判断最低位 通过 `n & 1` 判断当前最低位是否为1,如果是则计数加1,然后将 `n` 右移一位继续判断。
快速计算技巧
- 方法一: 使用 `n & (n - 1)` 将最低位的1变为0,循环执行直到 `n` 变为0,每执行一次循环计数加1。 - 方法二
二、示例代码(Java实现)
```java
public class CountonesInBinary {
// 方法一:使用 n & (n - 1)
public static int countonesUsingAndOperation(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
// 方法二:使用 n % 2 和 n / 2
public static int countonesUsingModuloOperation(int n) {
int count = 0;
while (n > 0) {
count += n % 2;
n /= 2;
}
return count;
}
// 方法三:使用 Brian Kernighan 算法
public static int countonesUsingBrianKernighan(int n) {
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
return count;
}
public static void main(String[] args) {
int number = 29; // 二进制为 11101
System.out.println("Number of 1s in binary: " + countonesUsingAndOperation(number));
System.out.println("Number of 1s in binary: " + countonesUsingModuloOperation(number));
System.out.println("Number of 1s in binary: " + countonesUsingBrianKernighan(number));
}
}
```
三、时间复杂度分析
最优方法(Brian Kernighan算法):每次循环将最右边的1变为0,因此时间复杂度为 O(k),其中 `k` 是二进制中1的个数。
其他方法:时间复杂度为 O(log n),适用于1较少的情况。
四、注意事项
以上方法适用于 32位无符号整数。若涉及更大整数,需使用位掩码或语言特性(如Java的 `Long.bitCount` 方法)。
位运算在性能敏感场景(如高频调用)中优势显著,建议优先采用中的高效方法。
通过上述方法,可快速准确计算整数的二进制表示中1的个数,适用于编程面试或性能优化场景。