# Run time error for my code !

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

Last executed input: 1.00000, -2147483648

However, my code below works! I just change one line! But, I think both are same!

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

if(n%2) return x*pow(x*x, n/2);
else return pow(x*x, n/2);
}
}
``````

;
I have no idea what the bug is in my first version. Thanks for your help!

• int: -2147483648 ~ 2147483647, n = -2147483648, -n = -2147483648, so in your first version,
infinite loop happens at this line : if(n<0) return pow(1/x, -n);

• But why my second version works fine? There is no difference between them.

• I found error in your first version. Consider the case: x = some double, n = -2147483648, then we know -n = n. So in you first code, " if(n<0) return pow(1/x, -n) " will be executed in a
infinite loop, because you simply use return and so the following two lines:
if(n%2) return xpow(xx, n/2);
else return pow(x*x, n/2);
will never get a chance to execute, because n is always less than 0 and you are always executing: if(n<0) return pow(1/x, -n);

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