Implement pow(x, n).
double pow(double x, int n) {
double result = 1;
double fact = x;
//先把特殊情况排除掉
/* if (n == 0)
return 1;
if (x == 1 || x == 0)
return x;
if (x == -1)
return n % 2 == 0 ? 1 : -1;*/
if (n < 0)
{
fact = 1 / x;
result = fact;
n = -(n + 1);//防止最小负数
}
while (n)
{//下面的逻辑理解是此题解题关键
while (n % 2 == 0)
{
fact *= fact;
n /= 2;
}
result *= fact;
n -= 1;
}
return result;
}