题目:

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0

思路:

还是矩阵快速幂,只是要细分double幂的为0情况为负情况:base==0和!=0, r>0/r<0/r=0;
1.base==0:
              r>0 return0;
              r<0 error;
2.base!=0:
              r>0 return base^r;
              r<0 return 1/base^r;
              r==0 return 1;
普通快速幂版:

class Solution {
public:
    double Power(double base, int exponent) {
        if(base == 0 && exponent > 0)
            return 0;
        if(base == 0 && exponent < 0){
            cout<<"divide 0";
            return 99999999999;
        }
        if(exponent == 0)
            return 1;
        double result = 1;
        int r = exponent;
        while(r){
            if(r % 2){
                result *= base;
            }
            base = base*base;
            r /= 2;
        }
        return exponent>0?result:1/result;
    }
};

递归快速幂(补单base的时机不一样,且base本身也不一样,a^10=a^5 * a^5=(a^2a) * (a^2a),上一版本:a^10=(aa)^5=((aa)(aa))^2 * (aa),补单的是不同阶段的不同a^n)

class Solution {
public:
    double Power(double base, int exponent) {
        if(base == 0 && exponent < 0)
            return 99999999;
        if(base == 0)
            return 0;
       return (exponent < 0)? (1/recurrsion(base, -1*exponent)):recurrsion(base, -1*exponent);
    }
    double recurrsion(double base, int r){
        if(r==1)
            return base;
        if(r==0)
            return 1;
        double subResult = recurrsion(base, r/2);
        subResult = subResult*subResult;
        return (r%2)?subResult*base:subResult;
    }
};