c - 评估整数是否为 POT(二的幂)

标签 c algorithm bit-manipulation

<分区>

Possible Duplicates:
Query about working out whether number is a power of 2
How to check if a number is a power of 2

我需要这个原型(prototype)的函数体:

bool isPOT(int x);

所以它会返回例如 isPOT(3) = FALSE,但是 isPOT(8) = TRUE

什么是最漂亮/最简洁的算法?什么是最有效的?

PS:我很惊讶我在 SO 上找不到这个问题,所以我完全希望有人能检测到一些重复的问题。

PPS:有人可以创建 POT、NPOT、Power-Of-Two 标签吗?

最佳答案

bool IsPOT(int x)
{
    return (x > 0) && ((x & (x - 1)) == 0);
}

关于c - 评估整数是否为 POT(二的幂),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5202447/

相关文章:

c - 如何在 C 中的一行中设置多个位?

c++ - 如何通过动态规划方法解决这个问题?

c - 自动变量在函数调用之间保留值

c++ - X11 上的编辑框

c - 让贪婪算法适用于每个输入

python - 子集生成算法的时间复杂度

python - 能源消耗最大化

c++ - 如何在没有循环的情况下设置字节中的位

python - 将字符串二进制转换为单独的位 python dataframe

c++ - 如何在 C/C++ linux 中实现类似 invokeOnMainThread() 的函数?