Title Description
Given a double base type and floating-point type int integer exponent. Seeking exponent of the power base.
Ensure the base and exponent are not simultaneously 0
Ideas analysis
Determining whether the first base-method, special circumstances and then determine the exponential of 0, then the power values obtained, the cycle that multiplies the last negative final result according to the number of power.
Code
public double Power(double base, int exponent) {
if (base == 0) {
return 0;
}
double res = 1;
if (exponent == 0) {
return res;
}
int n = exponent > 0 ? exponent : -exponent;
for (int i = 1; i <= n; i++) {
res*=base;
}
return exponent >= 0 ? res : (1 / res);
}