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);
}
}
}