Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A power of three is written in base three as a single 1 followed by zeros. Instead of generating powers or using logarithms, the reference approach inspects the number's base-three digits and checks that exactly one digit is 1 and every other digit is 0.
Approach
- Initialize a flag indicating that no
1digit has been seen. - Repeatedly inspect the remainder modulo three. A zero is allowed; a one sets the flag unless a previous one was already found. Any other remainder causes rejection.
- Divide by three, rounding toward negative infinity: Python uses
//, and JavaScript usesMath.floorwith a normalized nonnegative remainder. For positive inputs, this removes the inspected base-three digit. - Once the number reaches zero, return the flag. Zero never sets it, and positive powers have exactly one qualifying digit. A negative input is rejected earlier or eventually reaches
-1, whose normalized remainder is two and causes rejection; it is never accepted.
class Solution:
def isPowerOfThree(self, n: int) -> bool:
seen_one = False
while n:
if n % 3 == 1:
if not seen_one:
seen_one = True
else:
return False
elif n % 3 != 0:
return False
n //= 3
return seen_oneComplexity analysis
Each iteration divides n by three with rounding toward negative infinity, giving O(log(2 + |n|)) worst-case time and O(1) auxiliary space under the 32-bit input constraint. Zero returns immediately; negative inputs are rejected no later than reaching -1, whose normalized remainder is two.
