题目:
Implement pow(x, n).
思路:
使用二分法:pow(x,n) = pow(x,n/2)*pow(x,n-n/2)
Code:
public double pow(double x, int n) {
if(n<0){
if( n == Integer.MIN_VALUE)
return 1.0/(x*pow(x,Integer.MAX_VALUE));
else
return 1.0/pow(x,-n);
}
if(n==0)
return 1.0;
double half = pow(x,n>>1);
if(n%2==0)
return half*half;
else
return half*half*x;
}
备注:
1. 注意n为负数的情况
2. MIN_VALUE 不等于 MAX_VALUE, 等于 MAX_VALUE+1
3. 还有一种 bit 处理的方法
Reference:
http://blog.csdn.net/fengbingyang/article/details/12236121