美文网首页
十. binary search 1 Pow(x, n)

十. binary search 1 Pow(x, n)

作者: 何大炮 | 来源:发表于2018-04-03 09:38 被阅读0次

    In order to limit its time complexity into nlog(n), binary search comes into my view.

    1. remember do not use **
    2. minus index is unavoidable here
    3. use recursion
    class Solution:
        """
        @param: x: the base number
        @param: n: the power number
        @return: the result
        """
        def myPow(self, x, n):
            # write your code here
            if not x:
                return 0
            if n < 0:
                pow = 1/self.myPow(x, -n)
                return pow
            if n == 0.0:
                return 1.0
            middle = n//2
            pow = self.myPow(x, middle)
            if n % 2:
                pow = pow*pow*x
            else:
                pow = pow*pow 
            return pow
    
    

    Bonus scene:
    What's the lambda expression?
    It is always used when we need a One-off function.
    lambda x: x * x == function multiplication(x){ return x * x}
    x is the variable
    x * x is the function

    Attention: Lambda is always followed by build-in function like filter or reduce or map(more)

    相关文章

      网友评论

          本文标题:十. binary search 1 Pow(x, n)

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