avatar
l*8
2
old problem. you need 5 ">>", 10 "&" and 5 "+" but no branching
avatar
T*9
3
看x&x-1多久到0

【在 s***e 的大作中提到】
: 怎样统计一个unsigned int中1的个数.
: 请教最有效的算法.

avatar
l*8
4
"看x&x-1多久到0" is in fact not so good because the loop has conditional
branches, and in the worst case the loop has 32 iterations.
Try this. Although it looks ugly, it's at least 4x faster than the "while(x){i++;x&=(x-1);}" method.
int countbit_fast(int x)
{
x = ((x >> 1) & 0x55555555) + (x & 0x55555555);
x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
x += (x >> 4);
x &= 0x0f0f0f0f;
x += (x >> 8);
x += (x >> 16);
x &= 0x3f;
return x;
}
avatar
X*r
6
这个问题也太老了吧,N年前就流传开了,当时还在版上讨论过,在我被面试的时候居
然被问到了。
其实还有一种有效的方法:查表法,也可以查表和移位加相结合。

x){i++;x&=(x-1);}" method.

【在 l***8 的大作中提到】
: "看x&x-1多久到0" is in fact not so good because the loop has conditional
: branches, and in the worst case the loop has 32 iterations.
: Try this. Although it looks ugly, it's at least 4x faster than the "while(x){i++;x&=(x-1);}" method.
: int countbit_fast(int x)
: {
: x = ((x >> 1) & 0x55555555) + (x & 0x55555555);
: x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
: x += (x >> 4);
: x &= 0x0f0f0f0f;
: x += (x >> 8);

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。