首页 > 代码库 > Pow(x, n)

Pow(x, n)

题目

Implement pow(xn).

方法

注意Integer.MIN_VALUE值和Integer.MAX_VALUE值。
    public double pow(double x, int n) {

    	if (n == 0) {
    		return 1;
    	}
        if (n == Integer.MIN_VALUE && x == -1) {
    		return 1;
    	}
    	boolean flag = false;
    	if (n < 0) {
    		n = - n;
    		flag = true;
    	}
        double pro = 1;
        double remain = 1;
        double cur = x;
        
        while (n > 1) {
            if ((n & 1) == 1) {
                remain = remain * cur;
            }
            n = n >> 1;
            cur = cur * cur;
            
        }
        pro = cur * remain;
        if (flag) {
        	pro = 1 / pro;
        }
        return pro;
    }