Leetcode50-Pow(x,n)

2018-05-21  本文已影响14人  BlueSkyBlue

题目:

Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:
Input: 2.00000, 10
Output: 1024.00000

Example 2:
Input: 2.10000, 3
Output: 9.26100

Example 3:
Input: 2.00000, -2
Output: 0.25000

Note:


思路:

这道题可以采用二分法来做。首先观察n。


代码:

/**
     * Calculating pow(x, n).
     * @param x
     * @param n
     * @return
     */
    public double myPow(double x, int n) {
        if(x == 0){
            return 0.0;
        }
        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;
        double mid = Pow(x, n/2);
        if(n%2 == 0){
            return mid * mid;
        }else{
            return mid * mid * x;
        }
    }
上一篇下一篇

猜你喜欢

热点阅读