Pow(x, n)

Pattern: Maths basics

medium

Raise x to the power n in about log n multiplications by squaring x and reading n one bit at a time.

The problem

You are given a decimal number x (between -100 and 100) and a 32-bit integer n, which may be negative. Return x raised to the power n. A negative power means one over the positive power, so 2 to the power -2 is 1/4 = 0.25. The inputs are chosen so the answer stays within a normal decimal number's range.

The function name myPow matches LeetCode. Use the link above for the exact statement.

Think first

  • How many multiplications does 2¹⁰ take if you multiply one 2 at a time? What about 2 to the power 2 billion?
  • 2¹⁰ = (2²)⁵. And 2⁵ = 2 × 2⁴. Can you keep splitting like that?
  • What should happen when n is negative? And when it is the most negative 32-bit value?

Hints

    Brute force, and why it fails

    Multiply result by x exactly |n| times. That is correct, but for n near 2 billion it is 2 billion multiplications, several seconds of work, and too slow on a judge. A recursive version that does x × pow(x, n - 1) is worse: it also needs 2 billion nested calls and overflows the call stack.

    The key insight

    Squaring doubles the exponent in one multiplication. By squaring x and using the squares that match the 1 bits of n, any power takes about log₂ n steps: 31 or 32 rounds for any 32-bit n.

    Dry run

    10 
    01 
    12 
    03 
    power10
    x2
    result1

    x = 2 and n = 10. n is not negative. result starts at 1. In binary 10 is 1010, shown in the array. We read it from the right.

    Step 1 of 6

    The plan

    power = n                        # stored in 64 bits, so -n cannot overflow
    if power < 0:
        x = 1 / x
        power = -power
    result = 1
    while power > 0:
        if power mod 2 == 1:         # the lowest bit is 1
            result = result * x
        x = x * x                    # x stands for the next power of two
        power = power div 2          # move on to the next bit
    return result
    

    Complexity

    Time
    O(log n)
    Space
    O(1)

    The power halves every round, so there are about 32 rounds for any 32-bit n. The loop keeps only three variables.

    Edge cases

    • n = 0 returns 1, because the loop does not run.
    • Negative powers: 2 to the power -2 is 0.25.
    • n = -2147483648: negating it needs 64 bits. With x = 2 the answer is so small it rounds to 0.
    • x = 1 or x = -1 with a huge n stay 1 or ±1. The sign depends on whether n is odd.
    • x = 0 with a positive n is 0.
    I've built my logic, show the code

    Java

    class Solution {
        public double myPow(double x, int n) {
            long power = n;
            if (power < 0) {
                x = 1 / x;
                power = -power;
            }
            double result = 1;
            while (power > 0) {
                if (power % 2 == 1) {
                    result = result * x;
                }
                x = x * x;
                power = power / 2;
            }
            return result;
        }
    }

    C++

    class Solution {
    public:
        double myPow(double x, int n) {
            long long power = n;
            if (power < 0) {
                x = 1 / x;
                power = -power;
            }
            double result = 1;
            while (power > 0) {
                if (power % 2 == 1) {
                    result = result * x;
                }
                x = x * x;
                power = power / 2;
            }
            return result;
        }
    };

    Python

    class Solution:
        def myPow(self, x: float, n: int) -> float:
            power = n
            if power < 0:
                x = 1 / x
                power = -power
            result = 1.0
            while power > 0:
                if power % 2 == 1:
                    result = result * x
                x = x * x
                power = power // 2
            return result

    Common mistakes

    • Negating n in a 32-bit int. -(-2147483648) overflows back to -2147483648.
    • Forgetting to multiply into the result when the power is odd, which loses factors.
    • Recursing on n - 1 instead of n / 2, which is still linear and overflows the stack.
    • Squaring the result instead of x.

    Similar problems