代表数字7的8位像这样:
00000111
设置了三个比特。
确定32位整数中设置位数的算法是什么?
代表数字7的8位像这样:
00000111
设置了三个比特。
确定32位整数中设置位数的算法是什么?
当前回答
我个人使用这个:
public static int myBitCount(long L){
int count = 0;
while (L != 0) {
count++;
L ^= L & -L;
}
return count;
}
其他回答
一个简单的方法,应该工作得很好少量的比特它像这样(在这个例子中的4位):
(i & 1) + (i & 2)/2 + (i & 4)/4 + (i & 8)/8
对于少量的比特,其他人会推荐这种简单的解决方案吗?
这也可以正常工作:
int ans = 0;
while(num) {
ans += (num & 1);
num = num >> 1;
}
return ans;
从Python 3.10开始,你将能够使用int.bit_count()函数,但目前,你可以自己定义这个函数。
def bit_count(integer):
return bin(integer).count("1")
我总是在竞争性编程中使用它,它很容易写,而且效率很高:
#include <bits/stdc++.h>
using namespace std;
int countOnes(int n) {
bitset<32> b(n);
return b.count();
}
def hammingWeight(n):
count = 0
while n:
if n&1:
count += 1
n >>= 1
return count