可能显示的文件: Query关于制定是否数是2 电源 如何检查是否一个数是电源2
我需要一个函数体原型:
布尔isPOT(INT X);
那么它将返回如isPOT(3)= FALSE,但isPOT(8)= TRUE
什么是最pretty的/简洁的算法?什么是最有效的?
PS:我很惊讶,我找不到所以这个问题,所以我完全期待有人来检测一些重复
PPS:可有人请创建POT,NPOT,幂的两个标签
解决方案 布尔IsPOT(INT X)
{
则返回(x大于0)及&安培; ((X安培;(X - 1))== 0);
}
Possible Duplicates: Query about working out whether number is a power of 2 How to check if a number is a power of 2
I require a function body for this prototype:
bool isPOT(int x);
So it would return eg isPOT(3) = FALSE, but isPOT(8) = TRUE
What is the most pretty/concise algorithm? And what is the most efficient?
PS: I am amazed that I cannot find this question on SO, so I am fully expecting someone to detect some duplicate.
PPS: can someone please create POT, NPOT, Power-Of-Two tags?
解决方案bool IsPOT(int x)
{
return (x > 0) && ((x & (x - 1)) == 0);
}