[leetcode]Pow(x, n)

借鉴了之前加法的超时经验,就开始采用倍增法。但还是吃了负数和整数边界值的亏。最后干脆使用long得了。参考答案的递归果然更简洁易懂,而且不用考虑整数边界值的情况,精彩。

public class Solution {

    public double pow(double x, int n) {

        // Start typing your Java solution below

        // DO NOT write main() function

        

        double ans = 1;

    	double tmp = x;

        boolean neg = false;

        long m = n;

        if (m < 0) {

            neg = true;

            m = -m;

        }

    	long bound = m;

    	

    	while (bound != 0) {

    		long i = 1;

	    	for (; i*2 <= bound; i*=2) {

	    		tmp = tmp * tmp;

	    	}

	    	ans *= tmp;

	    	tmp = x;

	    	bound = bound - i;

    	}

        

        if (neg) return 1.0 / ans;

    	

    	return ans;

    }

}

参考答案:http://discuss.leetcode.com/questions/228/powx-n

double pow(double x, int n) {

    if (n == 0) return 1.0;

    // Compute x^{n/2} and store the result into a temporary

    // variable to avoid unnecessary computing

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

    if (n % 2 == 0)

        return half * half;

    else if (n > 0)

        return half * half * x;

    else

        return half * half / x;

}

第二刷:要注意n是负数的情况,还有负到头~

class Solution {

public:

    double pow(double x, int n) {

        if (x == 0 || x == 1) return x;

        if (n < 0 && n != INT_MIN) return 1.0 / pow(x, -n);

        if (n == 0) return 1.0;

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

        if (n % 2 == 0) {

            return p * p;

        } else {

            return p * p * x;

        }

    }

};

  

你可能感兴趣的:(LeetCode)