Skip to content

Latest commit

 

History

History
48 lines (38 loc) · 748 Bytes

050._pow(x,_n).md

File metadata and controls

48 lines (38 loc) · 748 Bytes

50. Pow(x, n)

题目: https://leetcode.com/problems/powx-n/

难度:

Medium

Recursive

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 == 0:
            return self.myPow(x*x, n/2)
        else:
            return x * self.myPow(x*x, n/2)
        

iterative

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