Premiumlab  

https://leetcode.com/problems/powx-n/#/description

 

 

Implement pow(xn).

 

 

Sol:

Recursion.

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

 

 

 

Sol 2 :

iteration.

 

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        # iteration
        
        res = 1
        if n < 0:
            n = - n
            flag = 1
        else:
            flag = 0
            
        while n > 0:
            if n % 2 == 1:
                res *= x
            x *= x
            n /= 2
        
        if flag == 0:
            return res
        else:
            return 1.0/res
            

 

posted on 2017-07-13 18:21  Premiumlab  阅读(123)  评论(0编辑  收藏  举报