数值的整数次方(剑指Offer)

 /**
     * 题目:数值的整数次方
     * 描述:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
     * 知识点:不能只考虑正数
     *
     * @param base
     * @param exponent
     * @return
     */
    //递归
    public double Power(double base, int exponent) {
        int t = Math.abs(exponent);
        if (exponent == 0) return 1.0;
        else if (exponent == 1) return base;
        double temp = Power(base, t / 2);
        if (t % 2 == 1) temp = temp * temp * base;
        else temp = temp * temp;
        if (exponent < 0) temp = 1 / temp;
        return temp;
    }





    //非递归的快速幂
    public double Power_(double base, int exponent) {
        int exp = Math.abs(exponent);
        double res = 1.0;
        while (exp != 0) {
            if ((exp & 1) != 0) res *= base;
            base *= base;
            exp >>= 1;
        }
        return exponent < 0 ? 1 / res : res;
    }

你可能感兴趣的:(剑指Offer题解,数据结构)