Pow(x,n) Problem Solution

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

Example :

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

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


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment