Pow(x, n)

Implement pow(x, n). x is double type and n is a integer type.

这是一道设计题,实现pow方法。主要考察对细节的处理,比如当n为负数时我们应该如何处理,仅仅是将n变为正数取倒数吗,如果当n为MIN_VALUE就会溢出,这种情况我们就要单独处理。此外我们通过右移来提高运算速度,每右移一次,x都加倍。实现代码如下:
public class Solution {
    public double myPow(double x, int n) {
        if(n == 0) return 1.0;
        if(n < 0) {
            if(n == Integer.MIN_VALUE) 
                return 1.0 / myPow(x, Integer.MAX_VALUE) * x;
            return 1.0 / myPow(x, -n);
        }
        double res = 1.0;
        for(; n > 0; n >>= 1) {
            if((n & 1) == 1)
                res *= x;
            x *= x;
        }
        return res;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2275078
今日推荐