Pow(n, x)题目总结

有关计算一个数幂的题目考查我们对于边界问题的处理,比如如何处理负数越界问题,以及如何通过位运算提高运算速度。这里列举leetcode中有关pow()方法的两道题目。

1,Power of Two
给定一个整数,判断这个数是否是2的幕。

这道题目比较简单,我们通过位与运算就可以解决,有关位运算的知识大家可以参考 位运算这篇文章。代码如下:
public class Solution {
    public boolean isPowerOfTwo(int n) {
        
        if(n < 0) return false;
        return (n & (n-1)) == 0;
     }
}


2,Pow(x, n)
实现Pow(x, n)方法。x为double型,n为int型。

这道题目考查我们如何处理越界问题,例如n为-128时,我们如果直接取绝对值,这时n就会越界,我们要单独考虑这种情况。其次为了提高运算速度,我们用位移来处理每次运算。实现代码如下:
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 ans = 1.0 ;  
        for(; n > 0; n >>= 1) {  
            if((n & 1) > 0)  
                ans *= x; 
                x *= x;
        }  
        return ans;  
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2268892