KatInterview

326. Power of Three

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to determine if a given integer n is a power of three. An integer n is a power of three if there exists an integer x such that n = 3^x. This means n must be one of 3^0, 3^1, 3^2, .... A few observations:

Solution

Power of Three in Python

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        # The problem specifies that n is a 32-bit signed integer.
        # The largest power of 3 that fits in this range is 3^19 = 1162261467.
        # If n is a power of three, it must be positive and a divisor of this number.
        # Conversely, any positive divisor of 3^19 must be a power of 3,
        # because 3 is the only prime factor of 3^19.
        return n > 0 and 1162261467 % n == 0

Power of Three in Java

class Solution {
    public boolean isPowerOfThree(int n) {
        // The largest power of 3 that fits in a 32-bit signed integer (Integer.MAX_VALUE) is 3^19 = 1162261467.
        // If n is a power of three, it must be positive and must be a divisor of this largest power.
        // The divisors of 3^19 are of the form 3^k where 0 <= k <= 19.
        // So, we check if n is positive and if it divides 1162261467.
        return n > 0 && 1162261467 % n == 0;
    }
}

Power of Three in C++

class Solution {
public:
    bool isPowerOfThree(int n) {
        // The largest power of 3 that fits in a 32-bit signed integer is 3^19 = 1162261467.
        // If n is a power of three, it must be positive and must be a divisor of this largest power.
        // The divisors of 3^19 are of the form 3^k where 0 <= k <= 19.
        // So, we check if n is positive and if it divides 1162261467.
        return n > 0 && 1162261467 % n == 0;
    }
};

Power of Three in TypeScript

function isPowerOfThree(n: number): boolean {
    // The largest power of 3 that fits in a 32-bit signed integer is 3^19 = 1162261467.
    // In JavaScript/TypeScript, all numbers are 64-bit floats, but the problem constraints
    // imply we're dealing with values within the 32-bit integer range.
    // The logic remains the same.
    // If n is a power of three, it must be positive and a divisor of this largest power.
    // The divisors of 3^19 are of the form 3^k where 0 <= k <= 19.
    return n > 0 && 1162261467 % n === 0;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.