美文网首页
Leetcode50-Pow(x, n)(Python3)

Leetcode50-Pow(x, n)(Python3)

作者: LdpcII | 来源:发表于2017-09-27 17:18 被阅读0次

    50. Pow(x, n)

    Implement pow(x, n).

    My Solution

    class Solution(object):
        myPow = pow
    

    Reference (转)

    1
    class Solution:
        def myPow(self, x, n):
            return x ** n
    
    2
    class Solution:
        def myPow(self, x, n):
            if not n:
                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)
    
    3
    class Solution:
        def myPow(self, x, n):
            if n < 0:
                x = 1 / x
                n = -n
            pow = 1
            while n:
                if n & 1:
                    pow *= x
                x *= x
                n >>= 1
            return pow
    

    相关文章

      网友评论

          本文标题:Leetcode50-Pow(x, n)(Python3)

          本文链接:https://www.haomeiwen.com/subject/nbguextx.html