326. Power of Three

1. Description

Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == $3^x$.

2. Example

Example 1:
Input: n = 27
Output: true

Example 2:
Input: n = 0
Output: false

Example 3:
Input: n = 9
Output: true

Example 4:
Input: n = 45
Output: false

3. Constraints

  • $-2^{31}$ <= n <= $2^{31} - 1$

4. Follow Up

Could you do it without using any loop / recursion?

5. Solutions

My Accepted Solution

n = number Time complexity: O($log_3n$)
Space complexity: O(1)

class Solution 
{
public:
    // bool isPowerOfThree(int n)
    bool isPowerOfThree(int number) 
    {
        if(number == 0) return false;
        
        while(true)
        {
            if(number == 1) return true;
            else if(number % 3 == 0) number /= 3;
            else return false;
        }
    }
};

5.1 Magic Number(Follow Up)

Time complexity: O(1)
Space complexity: O(1)

// 1162261467 is the largest number of three's power in the range of INT

class Solution 
{
public:
    // bool isPowerOfThree(int n)
    bool isPowerOfThree(int number) 
    {
        return number > 0 && 1162261467 % number == 0;
    }
};
Last updated:
Tags: Math
comments powered by Disqus