LeetCode | Pow(x, n)

Implement pow(xn).

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章