题目描述:
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不要考虑大数问题。
思路:
实现功能还是比较简单的,一个循环就可以完成。
这个题目考查的重点在于边界测试和负面测试。在这种数值的题目中一定要留意三种情况,即正数,负数,0。
注意以下几种情况:
1.底数为0,如果指数为负数,这是不合法的。
2.底数为0,指数也为非负数,没有意义。
2.底数不为0,如果指数为负数,按指数的绝对值为次数循环之后,结果要取倒数。
注意到这几点之后,代码就比较全面了。
public class PowerTest {
private static boolean inValidInput;
public static double power(double base, int exponent) {
if (equal(base, 0) && exponent < 0) {
inValidInput = true;
return 0;
}
int absExponent = exponent;
if (exponent < 0) {
absExponent = - exponent;
}
double result = powerWithUnsignedExponent(base, absExponent);
if (exponent < 0) {
result = 1.0 / result;
}
return result;
}
private static double powerWithUnsignedExponent(double base, int absExponent) {
double result = 1.0;
for (int i = 1; i <= absExponent; i++) {
result *= base;
}
return result;
}
public static boolean equal(double a, double b) {
if (a - b > -0.0000001 && a - b < 0.0000001) {
return true;
}
return false;
}
public static void main(String[] args) {
double result = power(2, -1);
if (inValidInput) {
System.out.println("输入有误");
} else {
System.out.println("result = " + result);
}
}
}
上面代码还有几点要注意的地方
1.两个小数的比较:== 并不能够正确的判断两个小数是否相等,这是因为计算机中并不能准备的表示每一个整数,比如0.1就不能准确的表示出来。只要|a-b|足够小就可以认为两个小数相等。
2.0的非负次幂没有意义,返回值并不重要,但是这并不是错误输入。
另外还有一个更高效的解法,利用下面的公式:
利用递归可以写出O(lgn)的代码
private static double powerWithUnsignedExponentEfficent(double base,
int absExponent) {
if (absExponent == 0) {
return 1;
}
if (absExponent == 1) {
return base;
}
double result = powerWithUnsignedExponentEfficent(base,
absExponent >> 1);
result *= result;
if ((absExponent & 0x01) == 1) {
result *= base;
}
return result;
}