50. Pow(x, n)
Implement pow(x, n).
Subscribe to see which companies asked this question
double myPow(double x, int n) {
//if (x == 0) return x;
if (n == 0) return 1.0;
//if (n == 1) return x;
if (n < 0)
{
if (n == INT_MIN)
return 1.0 / (myPow(x,INT_MAX) * x);
else
return 1.0 / myPow(x, -n);
}
double half = myPow(x, n>>1);
if (n % 2 == 0)
return half * half;
else
return half * half * x;
}