【发布时间】:2014-03-06 11:08:48
【问题描述】:
我的问题和Fastest way of computing the power that a "power of 2" number used?很相似:
将x=2^y 作为输入,我想输出y。
不同之处在于我使用 C 而不是 C++ 进行编码,而且我确信我的输入中只有一个位设置,所以我想知道是否有更有效的方法来解决这个问题。
这是我的尝试:
unsigned int get_power_of_two(unsigned int x)
{
unsigned int y=0;
for(unsigned int input=x; input>0; input=input>>1)
{
if(input & 1U)
{
break;
}
y++;
}
return y;
}
与@Dave 的答案中建议的查找表相比,这种效率是多少?
(同样,我用 C 编码,所以我没有像 lower_bound 这样的迭代器函数)
【问题讨论】:
-
这里描述了完成这个任务的五种方法:graphics.stanford.edu/~seander/bithacks.html
标签: c math bit-manipulation