Header Ad

Leetcode Pow(x, n) problem solution

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


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)



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);  
}


Post a Comment

0 Comments