Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Build confidence with an intuition-first walkthrough focused on math fundamentals.
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 == 3x.
Example 1:
Input: n = 27 Output: true Explanation: 27 = 33
Example 2:
Input: n = 0 Output: false Explanation: There is no x where 3x = 0.
Example 3:
Input: n = -1 Output: false Explanation: There is no x where 3x = (-1).
Constraints:
-231 <= n <= 231 - 1Problem summary: 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 == 3x.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math
27
0
-1
power-of-two)power-of-four)check-if-number-is-a-sum-of-powers-of-three)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #326: Power of Three
class Solution {
public boolean isPowerOfThree(int n) {
while (n > 2) {
if (n % 3 != 0) {
return false;
}
n /= 3;
}
return n == 1;
}
}
// Accepted solution for LeetCode #326: Power of Three
func isPowerOfThree(n int) bool {
for n > 2 {
if n%3 != 0 {
return false
}
n /= 3
}
return n == 1
}
# Accepted solution for LeetCode #326: Power of Three
class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n > 2:
if n % 3:
return False
n //= 3
return n == 1
// Accepted solution for LeetCode #326: Power of Three
impl Solution {
pub fn is_power_of_three(mut n: i32) -> bool {
while n > 2 {
if n % 3 != 0 {
return false;
}
n /= 3;
}
n == 1
}
}
// Accepted solution for LeetCode #326: Power of Three
function isPowerOfThree(n: number): boolean {
while (n > 2) {
if (n % 3 !== 0) {
return false;
}
n = Math.floor(n / 3);
}
return n === 1;
}
Use this to step through a reusable interview workflow for this problem.
Simulate the process step by step — multiply n times, check each number up to n, or iterate through all possibilities. Each step is O(1), but doing it n times gives O(n). No extra space needed since we just track running state.
Math problems often have a closed-form or O(log n) solution hidden behind an O(n) simulation. Modular arithmetic, fast exponentiation (repeated squaring), GCD (Euclidean algorithm), and number theory properties can dramatically reduce complexity.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.