describe
Given a floating-point number base of type double and an integer exponent of type int. Find the exponent power of base.
Make sure base and exponent are not 0 at the same time. Library functions are not allowed, and there is no need to consider large numbers or the number of 0s after the decimal point.
Example 1
input: 2.00000, 3
return value: 8.00000
example 2
input: 2.10000, 3
return value: 9.26100
example 3
input: 2.00000, -2
return value: 0.25000
analyze
Write a pow function, pay attention to the positive and negative of the index, and whether it is 0 or not.
the code
public class Solution {
private double MyPower(double base,int exponent){
if(exponent == 0) return 1;
if(exponent == 1) return base;
double tem = MyPower(base,exponent/2);
tem = tem*tem;
if(exponent%2==1){
tem = tem * base;
}
return tem;
}
public double Power(double base, int exponent) {
if(Math.abs(base) <= 0.00000001){
return 0;
}
if(exponent == 0){
return 1;
}
Boolean isNegative = (exponent<0);
double res = MyPower(base,exponent);
if(isNegative){
res = 1/res;
}
return res;
}
}