LeetCode – Pow(x, n)

Problem:

Implement pow(x, n).

This is a great example to illustrate how to solve a problem during a technical interview. The first and second solution exceeds time limit; the third and fourth are accepted.

Java Solution

public double myPow(double x, int n){
    if(n==0)
        return 1;
 
    if(n<0){
        return 1/helper(x, -n);
    }
 
    double v = helper(x, n/2);
 
    if(n%2==0){
       return v*v;
    }else{
       return v*v*x;
    }    
}

13 thoughts on “LeetCode – Pow(x, n)”

  1. this is a very good idea, I polish it a little as following in Java
    // nonrecursive implementation

    // its not the fast one, only runtime beats 29.88% of java submissions on 2/1/2016.

    static double power2(double x, int n) {

    if (x == 1) {

    return 1;

    }

    if (x == -1) {

    return n % 2 == 0 ? 1 : -1;

    }

    boolean negative = false;

    if (n >= 1;

    }

    return negative ? 1 / result : result;

    }

  2. best one:

    static double pow(double x, int n) {
    if (n == 0) return 1;
    double half = pow(x, n / 2);
    if (n % 2 == 0) return half * half;
    else if (n > 0) return half * half * x;
    else return half * half / x;
    }

  3. There is another simple solution for the problem

    public int pow(int x, int n) {
    int result = 1;

    while (n > 0) {
    if (n % 2 != 0) {
    result = result * x;
    }

    x = x * x;
    n = n / 2;
    }

    return result;
    }

  4. My solution :

    public double pow(int x, int n) {
    if (x == 0) return 0;
    if (n == 0) return 1;
    if(n<0) return 1/pow(x, -n);
    return x * pow(x, n – 1);
    }

  5. Thanks for solutions regarding this problem.

    Just a little remark regarding your third solution. The main issue is that it’s not actually using the advantage of that recursive definition. You shouldn’t actually call pow(x, half) * pow(x, half) as that’s doing the recursion twice to return the same result. Just store the value in a variable, and you should have log(n) computations.
    ie:
    int halfPower = pow(x, half);
    return halfPower * halfPower * pow(x, remainder);

Leave a Comment