Pow(x, n)
Implement pow(x, n).
public class Solution { public double pow(double x, int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int absn = Math.abs(n); if (absn==0.0) { //0的多少次方都是1 return 1.0; } if (absn==1) { //一次方是x本身 如果是负数取倒数 return n>0 ? x:1/x; } double ret = pow(x,absn/2); if (absn%2==0){ //例如2^4 看做2^2 * 2^2 如果是负数取倒数 return n>0 ? ret * ret : 1/(ret*ret); } else { //例如2^5 看做2^2 * 2^2 * 2 如果是负数取倒数 return n>0 ? ret * ret * x : 1/(ret * ret * x); } } }