返回题库

2 的幂判断

Power of 2

专题
Algorithmic Programming / 算法编程
难度
L4

题目详情

如何判断一个整数 xx 是否为 2 的幂?

英文原题

Is integer x a power of 2?

解析

判断 xx 是否为 2 的幂的常用位运算写法:

  • 要求 x>0x>0(排除 0 与负数)。
  • xx 的二进制表示中只有 1 个 bit 为 1。

等价条件:

(x>0)  (x & (x1)=0).(x>0)\ \wedge\ (x\ \&\ (x-1)=0).

因为若 xx2k2^k,则二进制为 1000...0,减 1 后为 0111...1,与运算为 0;反过来若与运算为 0,则只能有一个 1。


英文解析

Common bitwise operations to determine if xx is a power of 2:

  • Require x>0x>0 (excluding 0 and negative numbers).
  • and only 1 bit is 1 in the binary representation of xx.

condition of equivalence

(x>0)(x&(x1)=0).(x>0)\wedge(x \mathbin{\&}(x-1)=0).

Because if xx is 2k2^k, 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.