Skip to content

Problem

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 == 3x.

Constraints:

  • -231 <= n <= 231 - 1

Example 1:

**Input:** n = 27
**Output:** true
**Explanation:** 27 = 33

Solve


Actually using a computer to compute

We can use math to do it. Which is trying to check if n = 3**x => x = log_3(n)

Need to consider some off by 1 changing between integer and float using trunc because of floating point error

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n <= 0:
            return False
        m = trunc(log(n,3))
        return 3**m == n or 3**(m+1) == n

or equal c code

bool isPowerOfThree(int n){
    if (n <= 0) {
        return false;
    }

    int m = (int)trunc(log(n) / log(3));
    return pow(3, m) == n || pow(3, m + 1) == n;
}

Counting with loop

Looping until n == 0:

  • Check n mod 3 == 0, if not return False
  • Update n = n div 3

This to make sure we find n = 3 * 3 * 3 ... (k times), count the process and we can return the final k count number.

bool isPowerOfThree(int n){
    if (n == 0)
        return false;
    while (n != 1)
    {
        if (n % 3 != 0)
            return false;
        n = n / 3;
    }
    return true;
}

Last update : October 13, 2023
Created : August 16, 2023