Pow(x, n)

Medium MathRecursion

Problem

Implement pow(x, n)x raised to the power n. Works for negative powers.

Example 1 Input: x = 2.0, n = 10 Output: 1024.0
Example 2 Input: x = 2.1, n = 3 Output: 9.261
Example 3 Input: x = 2.0, n = -2 Output: 0.25

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class Solution:
    def myPow(self, x, n):
        if n < 0:
            x = 1 / x; n = -n
        res = 1.0
        while n:
            if n & 1:
                res *= x
            x *= x; n >>= 1
        return res

Java

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

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Pow(x, n) interactively → ← All solutions