数值的整数次方(代码的完整性)

题目描述:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。


思路一:简单快速幂法

public class Solution {
    public double Power(double base, int exponent) {
        int n = 0;
        double res = 1;
        double current = base;
        if (exponent > 0)
        {
            n = exponent;
        }
        else if (exponent < 0)
        {
            if (base == 0) throw new RuntimeException("分母不为0");
            n = -exponent;
        }
        else
        {
            if (base == 0) return 1;
            n = 0;
        }
        while (n != 0)
        {
            if ((n & 1) == 1) res = res * current;
            current = current * current;
            n = n >> 1;
        }
        return exponent >= 0 ? res : 1/res;
    }
}


思路二:递归

n为偶数,a^n = a^n/2 * a^n/2;

n为奇数,a^n=(a^(n-1)/2)*(a^(n-1/2))* a
时间复杂度O(logn)

public class Solution {
    public double Power(double base, int exponent) {
        int n = Math.abs(exponent);
        if (n == 0) return 1;
        if (n == 1) return base;
        double res = Power(base, (n >> 1));
        res *= res;
        if ((n & 1) == 1) res *= base;
        return exponent > 0 ? res : 1/res;
    }
}

思路三:传统解法

传统公式求解时间复杂度O(n)

public class Solution {
    public double Power(double base, int exponent) {
        if (base == 0 && exponent == 0) return 1;
        double res = 1;
        for (int i = 0; i < Math.abs(exponent); i++)
        {
            res *= base;
        }
        return exponent > 0 ? res : 1/res; 
    }
}

思路四:利用Math类的pow方法

public class Solution {
    public double Power(double base, int exponent) {
        if (base == 0.0 && exponent == 0) return 1.0;
        return Math.pow(base, exponent);
    }
}





你可能感兴趣的:(剑指offer)