题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
解题思路
public class shuzhidezhengshucifang {
public double cacluatePower(double base, int exponent) {
if (exponent == 1)
return base;
double val = cacluatePower(base, exponent >> 1);
double result = val * val;
if ((exponent & 1) == 1) {
result = result * base;
}
return result;
}
public double Power(double base, int exponent) {
if (exponent == 0)
return 1;
boolean negative = false;
if (exponent < 0) {
negative = true;
exponent = -exponent;
}
double result = cacluatePower(base, exponent);
if (negative) {
result = 1 / result;
}
return result;
}
public static void main(String[] args) {
System.out.println(new shuzhidezhengshucifang().Power(2, 3));
}
}