给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
double类型不能直接用==判断,底数等于0指数小于0时不能将0作为分母。
使用了优化的求幂函数
public class Solution {
public double Power(double base, int exponent) {
if (equal(base, 0) && exponent < 0) {
return 0.0;
}
int absExponent = Math.abs(exponent);
double result = powerWithExponent(base, absExponent);
if (exponent < 0) {
result = 1.0 / result;
}
return result;
}
public double powerWithExponent(double base, int absExponent) {
if ( absExponent == 0 )
return 1;
if ( absExponent == 1 )
return base;
double result = powerWithExponent(base, absExponent >>1);
result *= result;
if ( (absExponent&1) == 1 )
result *= base;
return result;
}
public boolean equal(double num1, double num2) {
if ((num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001)) {
return true;
} else
return false;
}
}