Count the number of 1’s in the binary expression of a given integer
Example:
input: 90
output: 4
用位操作。
public int countOnes(int x) {
int count = 0;
while (x != 0) {
x &= x - 1;
count++;
}
return count;
}
本文介绍了一种使用位操作来计算给定整数的二进制表示中1的数量的方法。通过一个示例展示了如何实现这一过程:输入为90时,输出为4。文中提供了一个简洁的Java函数实现。
Count the number of 1’s in the binary expression of a given integer
Example:
input: 90
output: 4
用位操作。
public int countOnes(int x) {
int count = 0;
while (x != 0) {
x &= x - 1;
count++;
}
return count;
}
2万+

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