算法思想:
如果我们要求x的n次幂,假定我们已经知道了x的n/2次幂,那么只需再平方即可,;
若n是奇数, =
*
* x , 若n是偶数,
=
*
,然后递归即可。
public static double myPow(double a, int b){
if (b < 0) {
a = 1/a;
b = -b;
}
return fastPow(a, b);
}
public static double fastPow(double a, int b){
if (b == 0) {
return 1.0;
}
double half = fastPow(a, b>>1);
if ((b & 1) == 1){
return half*half*a;
}else {
return half*half;
}
}
迭代法:
public static double myPow(double a, int b){
long c = (long)b;
if(c < 0){
a = 1/a;
c = -c;
}
double ans = 1.0;
while (c != 0){
if ((c & 1) == 1){
ans *= a;
}
a *= a;
c = c >> 1;
}
return ans;
}