Determine if a given integer is power of 2.

Examples

  • 16 is power of 2 (2 ^ 4)
  • 3 is not
  • 0 is not
  • -1 is not

Solution: 1. 是2的power的只有1位是1,其余为0; 2.用num & (num - 1)把最右端的1变为0,若是2的power,结果为0

results matching ""

    No results matching ""