Pow x n LeetCode Solution

Last updated on March 7th, 2025 at 09:33 pm

Here, we see a Pow x n LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Math, Recursion

Companies

Bloomberg, Facebook, Google, Linkedin

Level of Question

Medium

Pow(x n) LeetCode Solution

Pow(x n) LeetCode Solution

1. Problem Statement

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is “Exponentiation by Squaring”. This is a mathematical optimization technique used to compute powers efficiently. It is not part of the listed patterns but is a well-known algorithmic approach for solving power-related problems in logarithmic time.

3. Code Implementation in Different Languages

3.1 Pow(x n) C++

class Solution {
public:
    double myPow(double x, int n) {
        double res = 1;
        while (n) {
            if (n % 2) res = n > 0 ? res * x : res / x;
            x = x * x;
            n /= 2;
        }
        return res;    
    }
};

3.2 Pow(x n) Java

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

3.3 Pow(x n) JavaScript

var myPow = function(x, n) {
    if (n===0) return 1;
    let pow = Math.abs(n);
	let result = pow%2===0 ? myPow(x*x,pow/2) : myPow(x*x,(pow-1)/2) * x;
    return n < 0 ? 1/result : result;    
};

3.4 Pow(x n) Python

class Solution(object):
    def myPow(self, x, n):
        m = abs(n)
        ans = 1.0
        while m:
            if m & 1:
                ans *= x
            x *= x
            m >>= 1
        return ans if n >= 0 else 1 / ans

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(log n)O(1)
JavaO(log n)O(1)
JavaScriptO(log n)O(log n)
PythonO(log n)O(1)
  • The C++Java, and Python implementations use an iterative approach, which is more space-efficient ((O(1))).
  • The JavaScript implementation uses recursion, which results in an additional space complexity of (O(log n)) due to the recursion stack.
  • All implementations achieve logarithmic time complexity due to the halving of (n) in each step.

Scroll to Top