题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
代码示例
public class Offer11 {
public static void main(String[] args) {
Offer11 testObj = new Offer11();
System.out.println(testObj.power(2, 4));
System.out.println(testObj.power(2, 5));
}
public double power(double base, int exp) {
if (exp == 0) {
return 1;
}
if (exp == 1) {
return base;
}
boolean isNegative = false;
if (exp < 0) {
exp = - exp;
isNegative = true;
}
double pow = power(base * base, exp / 2);
if (exp % 2 != 0)
pow = pow * base;
return isNegative ? 1 / pow : pow;
}
}