DevPath

← All problems

Power of Three

Easy math

Description

Return true if n is an integer power of three.

Constraints

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

Examples

Input: n = 27

Output: true

Hints (1)
  • Repeatedly divide by 3; n must reach 1 exactly.

Solutions

Repeated division. · Time O(log n) · Space O(1)

func isPowerOfThree(n int) bool {
    if n < 1 {
        return false
    }
    for n%3 == 0 {
        n /= 3
    }
    return n == 1
}

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

Create account