[LeetCode] Pow(x,n) O(logN)

又一个Linkedin面试过的

public class Solution {
    public double pow(double x, int n) {
        int sign = 1;
        if(n < 0) {
            n = -n;
            sign = -1;
        }
        if(n == 0) return 1;

        double d = pow(x, n/2);

        if(n%2 == 0) return sign == 1 ? d*d : 1/(d*d);
        else return sign == 1 ? x*d*d:1/(x*d*d);

    }
}
posted on 2015-03-31 00:01  Seth_L  阅读(96)  评论(0编辑  收藏  举报