</>

50. Pow(x, n)

Medium NeetCode 150
Math & Geometry Time O(log n) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Math & Geometry
Time
O(log n)
Space
O(1)

Standard Solution (C++)

SummaryGiven a floating-point base x and an integer exponent n (which may be negative), compute x raised to the power n and return the result as a double.

Approach
  • Use binary exponentiation (fast power): at each step, if the current exponent bit is set, multiply the running result by the current base, then square the base and halve the exponent.
  • This reduces O(n) multiplications to O(log n) by exploiting the identity x^n = (x^2)^(n/2).
  • Handle negative exponents by taking the reciprocal of x and working with |n|; cast n to long first to safely negate INT_MIN without overflow.
#include <cmath>
using namespace std;

class Solution {
public:
    double myPow(double x, int n) {
        long exp = n;                  // avoid overflow when negating INT_MIN
        if (exp < 0) {
            x = 1.0 / x;
            exp = -exp;
        }

        double result = 1.0;
        // Binary exponentiation: O(log n) multiplications
        while (exp > 0) {
            if (exp & 1)               // odd exponent: absorb one factor
                result *= x;
            x *= x;                    // square the base
            exp >>= 1;                 // halve the exponent
        }
        return result;
    }
};
Time O(log n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    double myPow(double x, int n) {
        if(x==1 || n==0)
            return 1.0;
        if(x==-1)
            return (n%2)?-1.0:1.0;

        double res=1;
        long N=n;
        if(N<0){
            x=1.0/x;
            N=-N;
        }

        // 2^10 = 4^5 = 4^4 * 4 = 16^2 * 4 = 256*4
        while(N>1){
            if(N&1){
                res*=x;
            }
            x*=x;
            N>>=1;
        }
        res*=x;

        return res;
    }
};

// Time Complexity: O(log n)
// Space Complexity: O(1)
Time O(log n) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern