Power of Three
Given an integer n, return true if it is a power of three.
Example 1
Input: 27 → Output: true
Example 2
Input: 0 → Output: false
Solution Approach
The largest power of 3 that fits in a 32-bit integer is 3^19 = 1162261467. Any n that is a power of 3 must divide this number.
- If n <= 0: return false.
- Return 1162261467 % n == 0.
Java
class Solution {
public boolean isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
}
- Time Complexity: O(1)
- Space Complexity: O(1)