2 的幂判断
Power of 2
题目详情
如何判断一个整数 是否为 2 的幂?
英文原题
Is integer x a power of 2?
解析
判断 是否为 2 的幂的常用位运算写法:
- 要求 (排除 0 与负数)。
- 且 的二进制表示中只有 1 个 bit 为 1。
等价条件:
因为若 是 ,则二进制为 1000...0,减 1 后为 0111...1,与运算为 0;反过来若与运算为 0,则只能有一个 1。
英文解析
Common bitwise operations to determine if is a power of 2:
- Require (excluding 0 and negative numbers).
- and only 1 bit is 1 in the binary representation of .
condition of equivalence
Because if is , then binary is 1000... 0, minus 1 is 0111... 1, and operation is 0; conversely, if and operation is 0, there can only be one 1.