数值的整数次方非递归和递归的实现方式

    科技2024-11-13  7

    1. 非递归全面但不够高效的解法

    static double powerWithExponent1(double base, int exponent) { double result = 1.0; for (int i = 1; i <= exponent; i++) { result *= base; } return result; } static boolean gInvalidInput = false; //全局变量标识是否出错 static double powerWithExponent2(double base, int exponent) { gInvalidInput = false; if (base == 0.0 & exponent < 0) { //当底数是零且指数是负数的时候 gInvalidInput = true; return 0.0; } int absExponent = exponent; if (exponent < 0) absExponent = -exponent; double result = powerWithExponent1(base, absExponent); if (exponent < 0) result = 1.0 / result; return result; }

    2. 递归全面高效的解法

    static double powerWithExponent(double base, int exponent) { if (exponent == 0) return 1; if (exponent == 1) return base; if (exponent == -1) return 1/base; double result = powerWithExponent(base, exponent >> 1); //右移1位代替了除以2 result *= result; if ((exponent & 0x1) == 1) { //用位与运算代替了求余运算符来判断一个数是奇数还是偶数 return result * base; } return result; }
    Processed: 0.026, SQL: 8