326. Power of Three - Easy

Given an integer, write a function to determine if it is a power of three.

Example 1:

Input: 27
Output: true

Example 2:

Input: 0
Output: false

Example 3:

Input: 9
Output: true

Example 4:

Input: 45
Output: false

Follow up:
Could you do it without using any loop / recursion?

M1: use loop

time = O(log_3(n)), space = O(1)

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

M2: check if log10(n) / log10(3) is integer by taking the decimal part (using % 1) and checking if it is 0

time = the function Math.log10() takes, space = O(1)

class Solution {
    public boolean isPowerOfThree(int n) {
        return (Math.log10(n) / Math.log10(3)) % 1 == 0;
    }
}

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/11400471.html