快速幂
看看大佬的写法吧。 (降低了时间复杂度)
class Solution {
public double myPow(double x, int n) {
double res = 1.0;
for(int i = n; i != 0; i /= 2){
if(i % 2 != 0){
res *= x;
}
x *= x;
}
return n < 0 ? 1 / res : res;
}
}
还看的不是太懂,递归好理解,但是迭代就不太好理解。