Tuesday, October 27, 2015

[leetcode] Pow(x,n)

二分法...
不断地使用n/2的结果来结合出新的数...
一个Case是INT_MIN转成正数会overflow.所以先加一 再除回去。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Solution {
    public double myPow(double x, int n) {
        return n < 0?(1/recursivePow(x, Math.abs(n+1))/x): 
                     recursivePow(x, n);
    }
    
    private double recursivePow(double x, int n){
        if (n == 0){
            return 1;
        }
        double v = recursivePow(x, n/2);
        return n%2==0?v*v:v*v*x;
    }
}

No comments:

Post a Comment