Topic description
Given a float base of type double and an integer exponent of type int. Find the exponent power of base.
Make sure that base and exponent are not 0 at the same time
Thought analysis
- Pay attention to boundary judgment
- If it is 0, return directly
- If the exponent is negative, it needs to be calculated with base as the denominator
Code
public class Solution {
public double Power(double base, int exponent) {
double res = 1;
if (exponent == 0) {
return 1;
} else if (exponent < 0) {
while (exponent ++ < 0) {
res *= (1 / base);
}
} else if (exponent > 0) {
while (exponent-- > 0) {
res *= base;
}
}
return res;
}
}