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

class Solution {
    public boolean isPowerOfThree(int n) {
        while (n > 0 && n % 3 == 0) {
            n = n/3;
        }
        return n == 1;
    }
}

3. Time & Space Complexity

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

Last updated