剑指Offer(9)

题目:

  给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

解法:

  要考虑到底数为0,指数为负数的情况,这道题主要考的是对边界值的思考。

public class Solution {
public double Power(double base, int exponent) {
boolean g_InvaildInput = false; if(equals(base,0.0) && exponent<0){
g_InvaildInput = true;
return 0.0;
} int absExponent = exponent;
if(exponent<0)
absExponent = -exponent; double result = PowerWithExponent(base,absExponent); if(exponent<0){
result = 1.0 / result;
} return result;
} private double PowerWithExponent(double base, int exponent){
double result = 1.0;
for(int i = 1;i<=exponent;i++){
result *= base;
}
return result;
} private boolean equals(double numberOne,double numberTwo){
return Math.abs(numberOne - numberTwo)<0.000001;
}
}
上一篇:Java学习_int和Integer的区别+包装类


下一篇:JAVA中的clone方法剖析