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);
result *= result;
if ((exponent & 0x1) == 1) {
return result * base;
}
return result;
}
转载请注明原文地址:https://blackberry.8miu.com/read-34624.html