Skip to content
Problem 326 · LeetCode 326(opens in a new tab)

Power of Three

EasyMath

You are given a whole number n. Decide whether it is a power of three: is there a whole number x, zero or more, with 3 raised to x equal to n?

Return true if it is and false if it is not. Note that 1 counts, since 3 to the power 0 is 1.

Example 1

Input:  n = 243
Output: true
Why:    243 = 3 × 3 × 3 × 3 × 3
2 more examples and the constraints

Example 2

Input:  n = 45
Output: false
Why:    45 = 9 × 5, and 5 is not a 3

Example 3

Input:  n = -9
Output: false
Why:    every power of 3 is positive

Constraints

  • −2,147,483,648 ≤ n ≤ 2,147,483,647 (any 32-bit signed integer)
  • Follow-up: can you answer without a loop or recursion?

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Divide by 3 until you can'tO(log n)
  2. Divides the largest powerO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 1,162,261,467Verdict
Divide by 3 until you can'tO(log n)
Passes; the natural first answer
Divides the largest powerO(1)
Best; answers the follow-up

n = the input number; log n here is at most 19 divisions.

Edge cases to test

  • n = 1. 3 to the power 0 is 1, so the answer is true.
  • n = 0. No power of 3 is 0. The loop version would spin forever without the n <= 0 check.
  • Negative n. −243 looks like a power of 3 but is negative: false.
  • Divisible by 3 but not a power. 6 = 3 × 2 divides by 3 once, then leaves 2: false.
  • The largest power. 1,162,261,467 = 3^19 is true; 2,147,483,647 is false.

Common mistakes

  • Forgetting the n > 0 check, so 0 loops forever or causes a division by zero.
  • Using floating-point logarithms, where log(243) / log(3) can come out as 4.9999999 and round the wrong way.
  • Treating 1 as not a power of three, even though it is 3 to the power 0.

How to talk through it

  1. 1Clarify. Can n be zero or negative? Does 1 count as a power of three?
  2. 2Give the loop. Divide by 3 while it is exact; a power of 3 ends at 1. At most 19 passes.
  3. 3Use that 3 is prime. The divisors of 3^19 are exactly the powers of 3 up to 3^19.
  4. 4Code the one-liner. n > 0 and 1162261467 % n == 0, checking the sign first.
  5. 5Test out loud. Run 1, 0, −9, 45 and 243, and check true, false, false, false, true.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?