Community Problem

Power of Three

Difficulty: Easy

Decide whether a 32-bit signed integer is a power of three using a divisibility shortcut against the largest 32-bit power of three.

Power of Three

Decide whether a 32-bit signed integer is a power of three using a divisibility shortcut against the largest 32-bit power of three.

EASY
Free
math
bit-manipulation
ayomidegray

By @ayomidegray

January 30, 2026

·

Updated May 18, 2026

605 views

11

4.2 (11)

I caught this on a Datadog phone screen right after power-of-two. The follow-up they wanted was the no-loop, no-recursion solution, and the trick is that there is no two-bit identity for base 3. The clean answer leans on a number-theory observation that surprises people the first time they see it.

Power of Three

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

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

Examples

Example 1:

  • Input: n = 27
  • Output: true
  • Explanation: 3^3 == 27.

Example 2:

  • Input: n = 0
  • Output: false
  • Explanation: There is no integer x such that 3^x == 0.

Example 3:

  • Input: n = 9
  • Output: true
  • Explanation: 3^2 == 9.

Example 4:

  • Input: n = 45
  • Output: false
  • Explanation: 45 == 3^2 * 5, has a prime factor other than 3.

Example 5:

  • Input: n = 1
  • Output: true
  • Explanation: 3^0 == 1.

Constraints

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

Follow-up

Could you do it without loops or recursion? Yes, by precomputing the largest 32-bit power of three (3^19 == 1162261467) and checking divisibility, since powers of three are exactly the positive divisors of that number.

Solution

Hints

0/3
Hint 1
Hint 2
Hint 3
All Problems