Implement pow(xn).题目在这里,二分解法如下:

class Solution {
public:
    double pow(double x, int n) {
        double ans;
        if(n < 0){
            ans = power(x, -n);
            return (double)1 / ans;
        }else{
            return power(x, n);
        }
    }
    double power(double x, int n) {
        double ans;
        if(n == 0) ans=1;
        else
        {  ans=power(x*x, n/2);
           if(n%2==1) ans*=x;
         }
         return ans;
    }
};
      还可以这么写:

class Solution {
public:
    double pow(double x, int n) {
        double ans;
        if(n < 0)
            return (double)1 / power(x, -n);
        else return power(x, n);
    }
    double power(double a, int n) {
        double ans = 1;
        while(n > 0){
             if(n&1) ans *= a;   
             a *= a;
             n >>= 1;        
         }
         return ans;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

 posted on 2014-09-16 00:07  Rex7  阅读(197)  评论(0编辑  收藏  举报