# 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; } }```
Category >> Algorithms
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• Alik Elzin

Where’s the `helper()` method?

• Nikhil Bagde

Doesn’t work for base = 10 and power = 3
Gives result = 100.

• Bruce

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;

}

• Anushree Acharjee

the Best Solution given here has Overflow error. e,.g pow(71045970,41535484)

• hello

what if power < 0?

• carllee1991

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

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

• Amir

Iterative solution:

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

• Sébastien Dijols

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

• codeaperan

I have found a more concise solution from https://github.com/yuanx/leetcode/blob/master/Pow.java

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

• Dan

Need to handle: n=-2147483648.

• holey

cool solution 4.