题目:实现函数
double Power(double base, int exponent)
,求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
Java代码如下:
package demo;
public class Test10 {
public static double power(double base, int exponent) {
if(base == 0 & exponent == 0) {
throw new RuntimeException("invalid input. base and exponent are both zero!");
}
if(base == 0 & exponent < 0) {
return 0.0;
}
// 求幂次方
double result = powerWithUnsignedExponent(base, Math.abs(exponent));
if(exponent < 0) {
result = 1 / result;
}
return result;
}
/**
* 求正整数次幂
* @param base
* @param exponent
* @return
*/
private static double powerWithUnsignedExponent(double base, int exponent) {
if(exponent == 0) {
return 1;
}
if(exponent == 1) {
return base;
}
// 递归求一半的值
double result = powerWithUnsignedExponent(base, exponent >> 2);
result *= result;
if(exponent % 2 != 0) {
result *= base;
}
return result;
}
public static void main(String[] args) {
// 运行结果为false,说明可以直接用 == 表示2个小数是否相等
System.out.println(0.00000000000000000000000000000000000000000000001 == 0.0);
// 运行结果为true,说明写成0或者0.0都可以
System.out.println(0 == 0.0);
System.out.println(power(2, 4));
System.out.println(power(2, -4));
System.out.println(power(-2, 4));
System.out.println(power(-2, -4));
System.out.println(power(2, 0));
System.out.println(power(0, -4));
// System.out.println(power(0, 0));
System.out.println(power(0.0000000000000000000000000000000000000001, 0));
}
}