Andy Back-end Dev Engineer

剑指offer-数值的整数次方

2018-06-28

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

解体思路1

使用普通迭代求解幂次方

代码实现:(O(N))

public class Solution {
    public double Power(double base, int exponent) {
        boolean isNegative = false;
        double result = 1;
        
        if(exponent == 0) {
            return 1;
        } else if(exponent < 0){
            exponent = - exponent;
            isNegative = true;
        }
        
        for(int i=1; i<=exponent; i++) {
            result *= base;
        }
        
        return isNegative ? 1/result : result;
    }
}

解体思路2

代码实现:(O(logN))

public class Solution {
    public double Power(double base, int exponent) {
        boolean isNegative = false;
        if(exponent == 0)
            return 1;
        if(exponent == 1)
            return base;
        if(exponent < 0) {
            exponent = - exponent;
            isNegative = true;
        }
        
        double pow = Power(base * base, exponent/2);
        
        if(exponent % 2 != 0) 
            pow = pow * base;
         return isNegative ? 1/pow : pow;
    }
}

Comments

Content