LeetCode 50 Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (i.e. xn).
public double myPow(double x, int n)

this is actually a classic binary problem.
and the same as sqrt(x)

class Solution {
    public double myPow(double x, int n) {
        if (n > 0) {
            return pow(x, n);
        } else {
            return 1/pow(x, n);
        }
    }
    
    private double pow(double x, int n) {
        if (n == 0) return 1.0;
        
        double y = pow(x, n/2); //how are we gonna calculate x^n? 
        if (n % 2 == 0) { //
            return y * y;
        } else {
            return y * y * x;
        }
    }
}
posted @ 2020-11-09 04:31  EvanMeetTheWorld  阅读(22)  评论(0)    收藏  举报