Power of Three

Easy

Topics
MathRecursion

Given an integer n, return true if it is a power of three (i.e., n == 3^x for some non-negative integer x).

Example 1

76543210n = 2700011011
In binary a power of 3 has no tidy pattern, which is the point: the bit tricks that solve the power-of-two version do not transfer. Dividing by 3 while the remainder is zero is the honest check, and gives true.
Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input:  n = 27
Output: true

Example 2

76543210n = 000000000
Input:  n = 0
Output: false

Example 3

76543210n = 4500101101
Input:  n = 45
Output: false

Constraints

  • -2^31 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

Same shape as the powers of two and four, with one important difference: there is no bit trick. Three is not a power of two, so a power of three has no clean binary signature, and the shift-and-mask tricks do not transfer.

So divide by 3 while it divides evenly and check for 1. The positivity guard comes first.

There is a neat O(1) alternative specific to a fixed integer width: the largest power of three inside a signed 32-bit int is 3^19 = 1162261467, and because 3 is prime, every power of three divides it exactly. So n > 0 and 1162261467 % n == 0 settles it in one operation. Worth knowing, with the caveat that it depends entirely on the 32-bit bound and silently breaks if the range widens.

Approach

  1. Reject n <= 0.
  2. Divide by 3 while divisible; return whether 1 remains.

Dry Run

n = 27   27 -> 9 -> 3 -> 1   -> true
n = 45   45 -> 15 -> 5, then 5 % 3 != 0, 5 != 1  -> false
n = 1    1 % 3 != 0, and 1 == 1  -> true
n = 0    guard  -> false

Complexity

  • Time — O(log n) base 3, so at most 20 iterations in 32 bits. The divisor trick is O(1).
  • Space — O(1).

Common Pitfalls

  • Trying to adapt n & (n-1). It characterises powers of two only.
  • Omitting the positivity guard.
  • Using log-based tests, which lose precision — log(243)/log(3) can come out as 4.999999.
  • Using the 3^19 divisor trick without saying it assumes a 32-bit range. That assumption is the whole reason it works.

Full Solution — all languages

class Solution:
    def isPowerOfThree(self, n):
        if n <= 0:
            return False
        while n % 3 == 0:
            n //= 3
        return n == 1
SensAI
Beta
Tap the mic to stop voice mode