计算长位数中的置位位数 [英] Count number of Set bits in a long number
本文介绍了计算长位数中的置位位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要计算长整数中设置位的数量.另外,我需要优化相同.我正在使用以下代码:
I need to count number of set bits in a long number. Also I need to optimize the same. I'm using the following code:
public static int countSetBits(long number) {
int count = 0;
while (number > 0) {
++count;
number &= number - 1;
}
return count;
}
任何修改将不胜感激.
推荐答案
您可以按以下步骤编写而不加减法
You can write it without subtraction as follow
public static int countSetBits(long number) {
int count = 0;
while (number > 0) {
count += number&1L;
number>>=1L;
}
return count;
}
If You want to use Java's built-in libraries then can use bitCount
Long.bitCount(number)
如果您想查看 查看全文