# can someone tell me why the same code, one pass and one fail???

• double myPow(double x, int n) {
if (x == 0) return 0.0;
if (n < 0)
{
long long temp = -n;
return myPow(1/x, temp);
}
return helper(x, n);
}

``````double helper(double x, long long n)
{
if (n == 1) return x;
if (n == 0) return 1;
double temp = helper(x, n/2);
if (n%2 == 1) return temp * temp * x;
return temp * temp;
}

/**
* This works. Why?
*/
double myPow1(double x, int n) {
if (x == 0) return 0;
if (n < 0) return recursive(1/x, -n);
return recursive(x, n);
}

double recursive(double x, int n) {
if (n == 1) return x;
if (n == 0) return 1;
if (n%2 == 0) {
double temp = recursive(x, n/2);
return temp*temp;
}
else {
double temp = recursive(x, n/2);
return temp*temp*x;
}
}``````

• I have the similar problem. I think it because of the sequence of (n % 2 == 0) and (n % 2 == 1)
But I don't know the further cause.

• sorry, its not about the sequence, but about the if statement. if(n % 2 == 0) is ok, if(n % 2 == 1) is wrong

• because 2147483648 % 2 == -1

• @codermin cool. thanks very much

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