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



 

posted @ 2015-06-21 14:52  Mr.do  阅读(130)  评论(0编辑  收藏  举报