function divide(x,n){
if(n == 0)
return 1;
let subresult = divide(x,parseInt(n/2))
if(n&1 === 1){
return subresult*subresult*x;
}else{
return subresult*subresult
}
}
var myPow = function(x, n) {
if(n == 0)
return 1;
let num = parseFloat(x);
if(n < 0) {
num = 1/num;
n=-n;
}
return divide(num,n)
};
用分治法的思路 n&1是奇偶数的判断
还看到了有写的特别精简的写法
var myPow = function(x, n) {
if(n == 0) return 1;
if(n < 0) return 1/myPow(x,-n);
if(n%2) return x*myPow(x,n-1);
return myPow(x*x,n/2);
};