Implement pow(x, n).
负数次幂,直接转换成1/pow(x,-n),如果n=Integer.MINVALUE,转换成1/pow(x,INteger.MAXVALUE)/x,
一般的求x的n次幂,如果n是偶数,x^n=(x^(n/2))^2,转换成求n/2次幂再平方,如果n是奇数,
x^n=(x^(n/2))^2 * x,转化成求n/2次幂平方再乘x。
public class Solution {
public static double myPow(double x, int n)
{
if(x==1)
return 1;
if(n==1)
return x;
if(n==0)
return 1;
if(n<0)
{
if(n>Integer.MIN_VALUE)
return 1/myPow(x, -n);
return 1/myPow(x, Integer.MAX_VALUE)/x;
}
double half=myPow(x, n/2);
if(n%2==0)
return half*half;
else
{
return half*half*x;
}
}
}