可能重复:
Best algorithm to count the number of set bits in a 32-bit integer?
仅使用!~&^ << + >>运算符,我需要计算32位整数中设置的位数,同时只直接访问8位。所以只有0 0xaa而不是0 0xaa
例如。0x07 =3和0x05 =2
我也只能使用最多40个操作员。
现在,我的解决方案使用90,并且是:
int countBitsSet(int x)
{
int count = 0;
int mask = 0x01 // 00000001
count = (x & mask);
count += (x >> 1) & mask;
count += (x >> 2) & mask;
.
.
.
count += (x >> 31) & mask;
return count;
}有谁知道把这一步减半的办法吗?我正在想办法并行地做这件事,然后一次数4位,但我不知道怎么做。其他人已经在25家运营商这样做了,所以我知道有一个办法。有什么想法吗?
发布于 2011-09-01 14:57:56
( 1)计算错误的结果;31的偏移缺失。2)您应该使用for循环。3)搜索一点比特计数算法,就会给你提供一堆链接。
https://stackoverflow.com/questions/7272151
复制相似问题