Friday, August 1, 2014

[LeetCode] Pow(x,n)

Implement pow(x, n). 

解题思路:二分法,注意n < 0的情况


Java Code:

public double pow(double x, int n) {
        if(n == 0) return 1.0;
        int m = Math.abs(n);
        double result = 0.0;
        
        double tmp = pow(x, m/2);
        
        if(m%2 == 0){
            result = tmp*tmp;
        }else{
            result = tmp*tmp*x;
        }
        
        result = n < 0? 1.0/result : result;
        return result;
    }

No comments:

Post a Comment