Power of Three
Easy
Topics
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
true.Input: n = 27 Output: true
Example 2
Input: n = 0 Output: false
Example 3
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
- Reject
n <= 0. - 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 -> falseComplexity
- 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^19divisor 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 == 1import java.util.*;
class Solution {
public boolean isPowerOfThree(int n) {
if (n <= 0) return false;
while (n % 3 == 0) n /= 3;
return n == 1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isPowerOfThree(int n) {
if (n <= 0) return false;
while (n % 3 == 0) n /= 3;
return n == 1;
}
};/**
* @param {number} n
* @return {boolean}
*/ var isPowerOfThree = function(n) {
if (n <= 0) return false;
while (n % 3 === 0) n /= 3;
return n === 1;
};