Pow(x, n)

Implement pow(x, n)

这题用二分做,思路很明确,但是具体怎么做很有trick.

首先是n可能为INT_MIN ,如果将n直接取绝对值,则会溢出,另外,此时直接求分母,最后再求倒数,也可能在求分母的过程中溢出.

所以比较好的办法每次需要乘元素的时候乘以1/x(n<0)时.

大坑:python -1/2 = -1 , -1>>1 = -1. C++ -1/2=0, -1>>1=-1.一定要注意.

naive思路,c++可能会溢出的版本:

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        #binary search, each time wo only need to calculate the half pow
        if x == 0 and n < 0:
            return 0
        if n == 0:
            return 1
        res = self.pow_re(x, abs(n))  #此处如果为C++会溢出
        return res if n > 0 else 1.0/res #直接求分母也可能会溢出
        
    def pow_re(self, x, n):
        if n == 1:
            return x
        half = self.pow_re(x, n>>1)
        if n & 1 == 1:
            return half * half * x
        else:
            return half *half

改进版本,注意该版本无法在python中写:

class Solution {
public:
    double myPow(double x, int n) {
        if (n==0) return 1.;
        double half = myPow(x, n/2); //一定要这样写.
        return  n % 2 == 0? half*half: n > 0? half*half*x : 1/x*half*half ;
        
    }
};
原文地址:https://www.cnblogs.com/sherylwang/p/5779393.html