50.Pow(x, n)

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;
    }
};
class Solution {
    public double myPow(double x, int n) {
        if (n < 0)
            return 1/pow(x,-n);
        return pow(x,n);
    }
    private double pow(double x, int n) {
        if (n == 0)
            return 1;
        double res = pow(x, n/2);
        if (n%2 == 0) 
            return res * res;
        return x * res * res;
    }
}
posted @ 2019-04-09 10:15  JohnRed  阅读(109)  评论(0编辑  收藏  举报