Skip to content
Programmingoneonone
Programmingoneonone
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
  • Work with US
Programmingoneonone
Programmingoneonone

Leetcode Pow(x, n) problem solution

YASH PAL, 31 July 202418 January 2026

In this Leetcode Pow(x, n) problem solution, we need to implement pow(x, n), which calculates x raised to the power n (i.e., xn).

leetcode pow(x, n) problem solution

Leetcode Pow(x, n) problem solution in Python.

class Solution:
    def myPow(self, x: float, n: int) -> float:
        def pow(x, n):
            if n == 0:
                return 1
            
            r = pow(x, n//2)
            if n % 2 == 0:
                return r * r
            else:
                return r * r * x
            
        if n < 0:
            n *= -1
            x = 1/x
            
        return pow(x, n)

Pow(x, n) problem solution in Java.

public double myPow(double x, int n) {
    double[] stored = new double[32];
    stored[0] = x;
    for (int i = 1; i < 32; i++) stored[i] = stored[i-1] * stored[i-1];
    
    int exponent = n < 0 ? n == Integer.MIN_VALUE ? Integer.MIN_VALUE : -n : n;
    double ans = 1;
    for (int i = 0; i < 32; i++) {
        if ((exponent&(1<<i)) != 0) {
            ans *= stored[i];
        }
    }

    return n > 0 ? ans : 1/ans;
}

Problem solution in C++.

class Solution {
public:
    double myPow(double x, int n) {  
        if (x == 1.0) return x;
        uint32_t m = (n < 0 ? -static_cast<int64_t>(n) : n);
        double z = 1.0,  w = (n < 0 ? 1.0 / x : x);
        while (m != 0) {  
            if (m & 0x1UL) z *= w;
            w *= w;   
            m >>= 1;
        }
        return z;     
    }
};

Problem solution in C.

double myPow(double x, int n) {
    double res = 1;
    long absn;
    
    absn =  (n < 0) ? ((long)n * -1) : n;
    while (absn > 0) {
        if (absn & 1)
            res *= x;
        x *= x;
        absn >>= 1;
    }
    res = (n < 0) ? 1/res : res;
    return(res);  
}

coding problems solutions Leetcode Problems Solutions Leetcode

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes