Problem Description
Determine if a given integer n is a power of three. In other words, check whether there exists an integer x such that n equals 3 raised to the power x.
Key Insights
- The problem is defined in terms of exponents; we need to verify if n can be represented as 3^x.
- For n <= 0, the answer is always false since powers of three are positive.
- One clever method for a constant time solution involves using the fact that the maximum power of three that fits in a 32-bit signed integer divides any smaller power of three without a remainder.
Space and Time Complexity
Time Complexity: O(1)
Space Complexity: O(1)
Solution
We can use a mathematical trick to verify if n is a power of three.
- First, check that n is positive since negative numbers and zero cannot be a power of three.
- For the 32-bit integer range, the highest power of three is 3^19 (which equals 1162261467).
- If n is a divisor of 1162261467, then it must be a power of three because a power of three will divide a higher power of three exactly.
This approach uses basic arithmetic and does not involve any loops or recursion, aligning with the follow-up requirement.