首先需要讨论各种case:
- 如果 base == 0, 直接返回本身;
- 如果 exponent < 0, base取倒数,exponent取相反数;
再通过一个循环,得到 base ^ exponent。代码如下:
public class Solution {
public double Power(double base, int exponent) {
// Corner Case
if(base == 0){
return base;
}
double res = 1.0;
if(exponent < 0){
exponent = -1 * exponent;
base = 1 / base;
}
for(int i = 1; i <= exponent; i++){
res *= base;
}
return res;
}
}
可以通过recursion来取代循环,时间复杂度更低。