Leetcode Pow(x, n) problem solution

In the Leetcode Pow(x, n) problem solution 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

Constraints:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • n is an integer.
  • -104 <= xn <= 104

Solution in C Programming

double myPow(double x, int n){

    int i=0;
    double res = x;
    double tempx= x;

    if(n==0 || x==1){
        return 1;
    }

    if(n<0){
        res = 1/res;
        tempx = res;
        n=-1*n;
    }



    while(n > 1){

        res *= tempx;       

       n--; 
    }

    return res;
}

Solution in C++ Programming

class Solution {
public:
    double binaryExp(double x,long long n){
        if(n==0) return 1;
        double call = binaryExp(x,n/2);
        if(n&1) return x * call * call;
        else return call * call;
    }
    double myPow(double x, int num){
        long long n = num;
        return n < 0 ? 1 / binaryExp(x,-n) : binaryExp(x,n);
    }
};

Solution in Java Programming

import java.lang.Math;
class Solution {
    public double myPow(double x, int n) {
        return (double)Math.pow(x,n);
    }
}

Solution in Python Programming

class Solution:
    def myPow(self, x, n):
        # store base^exp tuples for each 
        stored = [(1,x)] # (exp,base^exp) lookup table of past calculations
        if x == 0: return 0.0
        if n == 0: 
            return 1
        elif n > 0:
            return power(stored, x,n-1)
        else:
            return 1/(power(stored, x,-(n+1)))
def power(stored, result, exp):
    if exp == 0:
        return result
    stored_exp, stored_result = find_largest_exp(stored,exp) 
    # update table
    largest_stored_exp = stored[-1][0]
    if largest_stored_exp < exp:
        stored.append((stored_exp*2,result*stored_result))
    return power(stored, result*stored_result, exp-stored_exp)

def find_largest_exp(stored,exp):
    for stored_exp, stored_result in stored[::-1]:
        if exp >= stored_exp:
            return (stored_exp, stored_result)

Solution in C# Programming

public class Solution {
    public double MyPow(double x, int n)
 {
   if(n < 0)
   {
       n *= -1;
       x = 1/x;
   }
     return Half(x,n);
  }

private double Half(double x, int n)
{
    if(n == 0)
        return 1.0;
    
    double half = Half(x, n/2);
    
    if(n%2 == 0)
        return half * half;
    else
        return half*half*x;
}
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

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