Leetcode:Pow(x, n)

Implement pow(xn).spa

分析:分治法。代碼以下:code

class Solution {
public:
    double pow(double x, int n) {
        if(n < 0) return 1.0/power(x, -n);
        return power(x, n);
    }
    
    double power(double x, int n){
        if(n == 0) return 1.0;
        double half = power(x, n/2);
        if(n%2 == 0) return half*half;
        return half*half*x;
    }
};
相關文章
相關標籤/搜索