剑指 Offer 16. 数值的整数次方

class Solution {
    public double myPow(double x, int n) {
        if(x == 1) return 1;
        if(x == -1) return n%2==0?1:-1;
        if(n<-1000) return 0;
        if(n<0) return 1.0/pow(x,-n);
        return pow(x,n);
    }

    private double pow(double x, int m) {
        if(m == 0) return 1.0;
        if(m == 1) return x;
        if(Math.abs(x)<=0.0001 && m>0) return 0;
        if(m%2==0) return pow(x,m/2)*pow(x,m/2);
        else return pow(x,m/2)*pow(x,m/2)*x;
    }
}

 

 


public double myPow(double x, int n) {
        if (n == -1) return 1/x;
        if (n == 0) return 1;
        if (n == 1) return x;
        double half = myPow(x, n>>1);
        return half * half * myPow(x, n&1);
    }

 

posted @ 2020-08-09 21:40  欣姐姐  阅读(132)  评论(0编辑  收藏  举报