/*
* 面试题16:数值的整数次方
* 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent的次方。
* 不得使用库函数,不需要考虑大数的问题。
*/
public class ExponentOfBase {
public static void main(String[] args) {
ExponentOfBase e = new ExponentOfBase();
System.out.println("0的0次方: "+e.power(0, 0));
System.out.println("1的0次方: "+e.power(1, 0));
System.out.println("0的1次方: "+e.power(0, 1));
System.out.println("2的2次方: "+e.power(2, 2));
System.out.println("2的-2次方: "+e.power(2, -2));
}
public double power(double base ,int exponent) {
double res = 0;
if (equal(base,0)) {
return 0.0;
}
if (exponent == 0) {
return 1.0;
}
if (exponent == 1) {
return base;
}
if (exponent > 1) {
res = mutiply (base,exponent);
} else {
res = mutiply(1/base,-exponent);
}
return res;
}
private double mutiply(double base, int exponent) {
double sum = 1;
for (int i = 0; i < exponent; i++) {
sum = sum * base;
}
return sum;
}
private boolean equal(double a, int b) {
if(a - b < 0.000001 && a - b > -0.000001) {
return true;
}
return false;
}
}
面试题16:数值的整数次方
最新推荐文章于 2020-05-13 17:39:00 发布