zoukankan      html  css  js  c++  java
  • 剑指offer 面试16题

    面试16题:

    题目:数值的整数次方

    题:实现函数double Power(double base, int exponent),求base的exponent次方、不得使用库函数,同时不需要考虑大数问题。

    解题思路:主题考虑底数为0.0,指数为负数的情况,此时可以利用全局变量指出g_InvalidInput为True,同时返回0.0

    解题代码:

    # -*- coding:utf-8 -*-
    class Solution:
        g_InvalidInput = False
        def Power(self, base, exponent):
            # write code here
            if base==0.0 and exponent<0:
                g_InvalidInput=True
                return 0.0
            if exponent>=0:
                return self.PowerWithUnsignedExponent(base,exponent)
            return 1.0/self.PowerWithUnsignedExponent(base,-exponent)
        
        def PowerWithUnsignedExponent(self,base,exponent):
            result=1.0
            for i in range(exponent):
                result *= base
            return result

    解题优化:上述代码PowerWithUnsignedExponent部分还可以优化如下:使用平方的一半*平方的一半来计算平方,此时时间复杂度为O(logn)。同时涉及除以2用右移运算符代替,判断奇偶数时用位与运算代替求余运算符,这样效率高很多。

    解题代码:

    # -*- coding:utf-8 -*-
    class Solution:
        def __init__(self):
            self.g_InvalidInput=False
        def Power(self, base, exponent):
            # write code here
            if base==0.0 and exponent<0:
                self.g_InvalidInput=True
                return 0.0
            if exponent>=0:
                return self.PowerWithUnsignedExponent2(base,exponent)
            return 1.0/self.PowerWithUnsignedExponent2(base,-exponent)
    
        def PowerWithUnsignedExponent2(self, base, exponent):
            if exponent==0:
                return 1
            if exponent==1:
                return base
            res=self.PowerWithUnsignedExponent2(base,exponent>>1)
            res *= res
            if exponent & 0x1==1:
                res*=base
            return res
  • 相关阅读:
    http修改443端口,http 强制跳转https
    线程event事件函数实现红绿灯
    信号量设置
    多线程简单实例
    paramiko 实现ssh登录和sftp登录
    在同一台电脑安装python 2 和3,并且怎样安装各自的pip和模块
    ThreadingTCPServer 如何设置端口重用
    Python 变量比较
    python 多线程 并发socket实例
    python 中变量引用问题
  • 原文地址:https://www.cnblogs.com/yanmk/p/9194769.html
Copyright © 2011-2022 走看看