DevPath

← All problems

Power of Two

Easy bit-manipulation · math

Description

Return true if n is an integer power of two.

Constraints

n is any integer

Examples

Input: n = 16

Output: true

Hints (1)
  • A positive power of two has exactly one set bit, so n & (n - 1) is zero.

Solutions

Single set-bit test. · Time O(1) · Space O(1)

func isPowerOfTwo(n int) bool {
    return n > 0 && n&(n-1) == 0
}

Create a free account to submit solutions, track progress and save problems.

Create account