Leetcode50 Pow(x,n)

Implement pow(xn).


Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100


剑指offer的解法(我的翻译)42ms,打败18.70%的答案:

class Solution(object):
    def myPow(self, base, exponent):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        def PowerWithUnsignedExponent(base,absex):
            if absex==0:#指数是0的时候,结果是1
                return 1
            if absex==1:
                return base
            result=PowerWithUnsignedExponent(base,absex>>1)
            result=result*result
            #假定input为base=3,ex=5
            #比如ex=5,101->右移一位:010-》右移一位 001
            #比如ex=5,5-->2-->1
            if(absex& 1 ==1):
                result=result*base
            return result
        
        g_invalid_input=False
        if base==0.0 and exponent<0:#对于非法输入的判断,底数为0指数是负数的时候非法,因为算1.0/result的时候不能除以0
            g_invalid_input=True
            return 0.0

        if exponent<0:#如果指数是负数
            absexponent=-exponent
        else:
            absexponent=exponent
            
        result=PowerWithUnsignedExponent(base,absexponent)
        if exponent<0:#如果指数是负数
            result=1/result
                
        return result
            

发现:

1.Python并不像剑指OFFER中所写的C++那样无法直接比较两个浮点数是否相等

2.对于本算法的理解,比如求3的5次方,依次求ex=5,ex=2,ex=1时(在此体会出右移的NB)

而if(absex& 1 ==1):
                result=result*base
这句话起作用

是在absex==5的时候

不是在absex==1的时候,因为absex==1的时候,在这句之前就已经 return base了




最快的解法28ms:

# StefanPochmann
class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        if n == 0:
            return 1
        if n < 0:
            return 1 / self.myPow(x, -n)
        if n % 2:
            return x * self.myPow(x, n - 1)
        return self.myPow(x * x, n / 2)

巧妙之处: 并不是按a的n次方=a的二分之n次方*a的二分之n次方这样方式划分的,而是 myPow(x*x,n/2)这样划分以减少计算次数的,当然同样巧妙了!

猜你喜欢

转载自blog.csdn.net/u011462357/article/details/79339875