[LeetCode] Pow(x, n) (二分法)

Implement pow(x, n).

刚开始没想到,后来看remlost的博客才写出来,代码很简练:

class Solution {
public:
    double pow(double x, int n) {
        if(n<0)
            return 1/power(x,-n);
        else
            return power(x,n);
    }
private:
    double power(double x, int n){
        if(n==0)
            return 1;
            
        double v = power(x,n/2);
        if(n%2==0)
            return v*v;
        else
            return v*v*x;
        
    }

};

 

posted @ 2014-08-21 09:54  Xylophone  Views(219)  Comments(0Edit  收藏  举报