题目:实现函数double Power(double base,int exponent) 求base的exponent次方。不得使用库函数,同时不需要考虑大数问题;
public class PowerBySelf {
public static void main(String[] args) {
Double base =new Double("12"); //为了和0.0进行比较,进行装箱操作
int exponent = 0;
System.out.println(power(base,exponent));
}
static boolean g_invalidInput = false; //用来判断是否是无效输入
public static double power(Double base, int exponent) {
Double checkBase = 0.0;
if(base.compareTo(checkBase)==0||base<0) { //compareTo(Double anotherDouble)返回0时表示相等
System.out.println("底数不能为0");
g_invalidInput = true;
return 0;
}
if(exponent==0)
return 1;
int e = Math.abs(exponent); //取绝对值
for(int i=1;i<e;i++) {
base *= base;
}
return exponent>0?base:1/base;
}
}
分析:因为用户输入的base可能是0,正数,负数。
1)当base是<0时,报错。
2)base==0时,用JavaDouble.compareTO()来表示两个Double数据进行比较。double x1== double x2 永远是false;
3)base>0时,一切正常。
exponent可能是0,正数,负数。
1)当exponent = 0时,我们返回1;
2)当exponent为负数时时,我们对其取绝对值,正常计算base值,读后返回1/base即可;
优化代码:
public class PowerBySelf {
public static void main(String[] args) {
Double base =new Double("3"); //为了和0.0进行比较,进行装箱操作
int exponent = 5;
System.out.println(power(base,exponent));
}
static boolean g_invalidInput = false; //用来判断是否是无效输入
public static double power(Double base, int exponent) {
Double checkBase = 0.0;
if(base.compareTo(checkBase)==0||exponent<0) { //compareTo(Double anotherDouble)返回0时表示相等
System.out.println("底数不能为0");
g_invalidInput = true;
return 0;
}
if(exponent==0)
return 1;
if(exponent==1)
return base;
double result = power(base, exponent>>1); //右移一位,相当于除以2;
result *= result;
if(exponent%2==1) //用来判断是否为奇数
result *= base;
return result;
}
}
分析:我们将2^16 拆分为(2^2)^8 这样优化代码。每次exponent变为原来的二分之一,base = base*base; 结果不变.