EasyBitwise Manipulation

Power of Two

Explanation & Solution

Description

Given an integer n, return true if it is a power of two. Otherwise, return false.

An integer n is a power of two if there exists an integer x such that n == 2^x.

Input: n = 1

Output: true

Explanation: 2^0 = 1

Constraints

  • -2^31 <= n <= 2^31 - 1

Follow up: Could you solve it without loops/recursion?

Approach

Bitwise Manipulation pattern

Key Insight

  • The guard n > 0 handles the edge case of n = 0 (which would incorrectly pass the bit test: 0 & -1 = 0)
  • Time: O(1) | Space: O(1)

Solution Code