十. binary search 1 Pow(x, n)


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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,178评论 0 10
  • 我今天要写一个故事。 我妈妈是一个强势的女人,至少在家里是这样,我妈妈管着财政大权,当时我爸爸还在家乡村子里的工厂...
    sid_9ff8阅读 1,288评论 0 0
  • “起来了!快点穿衣服去!” 一个貌似消失已久却又厌烦的熟悉声音将我砸醒。经过一系列严格标准的机械流程:穿衣服、刷牙...
    啊Leung阅读 1,774评论 6 3
  • 睡意朦胧,突发的大雨叫醒了我,终究还是下起了雨,可能这个日子有那么一些特别。 一直觉得我们生来就在学习告别,告别各...
    辰北阅读 1,522评论 0 1
  • 文/长木云伊 在车间实习,有时候能看到有用的东西,但多数时候还是很无聊。我们几个做完操,背完核心价值观,然后就去走...
    莫嗔堂堂主阅读 1,810评论 0 0

友情链接更多精彩内容