KatInterview

50. Pow(x, n)

MediumSolutions 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 implement the pow(x, n) function, which calculates x raised to the power of n. A naive approach of multiplying x by itself n times would be too slow, given that n can be as large as 2^31 - 1. This would lead to a Time Limit Exceeded error. Furthermore, the exponent n can be negative and can be the minimum value for a 32-bit signed integer (-2^31), which requires special handling to avoid overflow when negated.

Solution

Pow(x, n) in Python

class Solution:
    def myPow(self, x: float, n: int) -> float:
        # In Python, integers have arbitrary precision, so overflow of n is not an issue.
        # The logic, however, remains the same.

        # If n is negative, invert x and make the exponent positive.
        if n < 0:
            x = 1 / x
            n = -n
        
        result = 1.0
        # Use binary exponentiation (exponentiation by squaring).
        while n > 0:
            # If n is odd, multiply x to the result.
            # This corresponds to the bits that are '1' in the binary representation of n.
            if n % 2 == 1:  # can also be written as (n & 1)
                result *= x
            
            # Square x and halve n for the next iteration.
            # x becomes x^2, x^4, x^8, ...
            x *= x
            n //= 2  # Integer division
            
        return result

Pow(x, n) in Java

class Solution {
    public double myPow(double x, int n) {
        // Use long for the exponent to handle the case n = Integer.MIN_VALUE,
        // as -Integer.MIN_VALUE would cause overflow.
        long N = n;
        
        // If the exponent is negative, invert x and make the exponent positive.
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        
        double result = 1.0;
        // Use binary exponentiation (exponentiation by squaring).
        while (N > 0) {
            // If N is odd, multiply x to the result.
            // This corresponds to the bits that are '1' in the binary representation of N.
            if (N % 2 == 1) {
                result = result * x;
            }
            
            // Square x and halve N for the next iteration.
            // x becomes x^2, x^4, x^8, ...
            x = x * x;
            N = N / 2;
        }
        
        return result;
    }
}

Pow(x, n) in C++

class Solution {
public:
    double myPow(double x, int n) {
        // Use long long for the exponent to handle the case n = INT_MIN,
        // as -INT_MIN would cause overflow.
        long long N = n;
        
        // If the exponent is negative, invert x and make the exponent positive.
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        
        double result = 1.0;
        // Use binary exponentiation (exponentiation by squaring).
        while (N > 0) {
            // If N is odd, multiply x to the result.
            // This corresponds to the bits that are '1' in the binary representation of N.
            if (N % 2 == 1) { // can also be written as (N & 1)
                result *= x;
            }
            
            // Square x and halve N for the next iteration.
            // x becomes x^2, x^4, x^8, ...
            x *= x;
            N /= 2; // can also be written as N >>= 1
        }
        
        return result;
    }
};

Pow(x, n) in TypeScript

function myPow(x: number, n: number): number {
    // In JavaScript/TypeScript, numbers are 64-bit floats. Integers are safe up to
    // 2^53 - 1, which is much larger than a 32-bit int, so n won't overflow.

    // If n is negative, invert x and make the exponent positive.
    if (n < 0) {
        x = 1 / x;
        n = -n;
    }

    let result = 1.0;
    // Use binary exponentiation (exponentiation by squaring).
    while (n > 0) {
        // If n is odd, multiply x to the result.
        // This corresponds to the bits that are '1' in the binary representation of n.
        if (n % 2 === 1) {
            result *= x;
        }

        // Square x and halve n for the next iteration.
        // x becomes x^2, x^4, x^8, ...
        x *= x;
        // Use Math.floor for integer division for positive numbers.
        n = Math.floor(n / 2);
    }

    return result;
};

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.