# Short and easy to understand solution

• ``````public class Solution {
public double pow(double x, int n) {
if(n == 0)
return 1;
if(n<0){
n = -n;
x = 1/x;
}
return (n%2 == 0) ? pow(x*x, n/2) : x*pow(x*x, n/2);
}
}``````

• should we add
if(x == 0) return 0;

• This post is deleted!

• Should check the case where "x==0", otherwise, the function would encounter the divide-by-zero exception.

• very concise

• When n=Integer.MIN_VALUE, then n=-n will overflow.

• If n is Integer.MIN_VALUE, the code will have overflow runtime error.

• So how to handle that case?

• you need one additional if statement
...

if( n<0 )
{
if( n == Integer.MIN_VALUE)
{
++n;
n = -n;
x = 1/x;
return x * x * pow( x*x, n/2 );
}
n = -n;
x = 1/x;
}
...

• you need to consider INT_MIN;
Add like this:
if(n < 0) {
if(n == INT_MIN)
return 1.0/ (myPow(x, INT_MAX) * x);
else
return 1.0/myPow(x, -n);
}

• the type of x is double you can't use if(x==0)

• ``````    if (n < 0) {
return 1 / (x * myPow(x, -(n + 1)));
}``````

• What would be the complexity of this solution? I think it is constant time in worst case with 31 iterations.

• This code actually passed the following case!!

-1.00000

-2147483648

But how can the code make it??

• Similar idea (no overflow check): decreasing n by dividing by 2. After we get the return result, multiply by itself. If n is a odd number, multiply one x if n is position; otherwise, 1 / x.

``````public class Solution {
public double myPow(double x, int n) {
if(n == 0) return 1.;
double res = myPow(x, n / 2);
return n % 2 == 0 ? res * res : n < 0 ? res * res * (1 / x) : res * res * x;
}
}``````

• this case naturally passes, although n will overflow after taking -n, but it eventually will generate 1 as the result since x is -1. However, if you feed in -2 as x for example, the program will not pass.

• I tried 0.999999 with -2147483648 as customized case

the code fails as expected

• so,my question is : why when n=INT_MIN,the result is 1; it should be 0.

• so,my question is : why when n=INT_MIN,the result is 1; it should be 0.

• This can not pass the newly added test cases

2.00000
-2147483648

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.