Google
326 Power of Three

1. Question

Given an integer, write a function to determine if it is a power of three.
Follow up: Could you do it without using any loop / recursion?

2. Implementation

1
class Solution {
2
public boolean isPowerOfThree(int n) {
3
while (n > 0 && n % 3 == 0) {
4
n = n/3;
5
}
6
return n == 1;
7
}
8
}
Copied!

3. Time & Space Complexity

时间复杂度O(logn), 空间复杂度O(1)