Implement pow(x, n).
//tag提示用binary search,主要就是确定有多少个x来相乘。
//思想是对n进行二分。注意下n可能为负数
public class Solution {
public double myPow(double x, int n) {
if(n == 0) return 1;
double temp = myPow(x, n/2); //对n来二分,来确定有多少个x相乘
//进行了logn次递归调用,故算法复杂度为O(logn)
if(n%2 == 0){
return temp * temp;
}
if(n > 0){
return temp * temp * x;
}else{ //n为负数时
return temp * temp * (1/x);
}
}
}