面试题16:数值的整数次方

2019-10-06  本文已影响0人  scott_alpha

题目:实现函数double power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
思路:先判断指数大小,分为正数,0和负数三种情况,分别处理。计算平方的时候,运用斐波那契原理减少重复计算。
解决方案:

public class Question16 {

    private static boolean invalidInput = false;
    public static double Power(double base, int exponent) {
        invalidInput = false;
        double result;
        if (exponent > 0){
            result = PowerWithUnsignedExponent(base, exponent);
        } else if (exponent < 0){
            if (base == 0){
                invalidInput = true;
                return 0.0;
            }
            result = 1 / PowerWithUnsignedExponent(base, -exponent);
        }else {
            return 1;
        }
        return result;
    }

    private static  double PowerWithUnsignedExponent(double base, int exponent) {
        if (exponent == 0) {
            return 1;
        }
        if (exponent == 1) {
            return base;
        }
        double result = PowerWithUnsignedExponent(base, exponent >> 1);
        result *= result;
        if ((exponent & 0x1) == 1) {
            result *= base;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(Power(5, 2));
    }
}
上一篇下一篇

猜你喜欢

热点阅读