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
  • 相关阅读:
    SQL Server系统表sysobjects介绍
    tofixed方法 四舍五入
    (function($){})(jQuery);
    DOS批处理命令-字符串操作
    IF ERRORLEVEL 和 IF %ERRORLEVEL% 区别
    Gpupdate命令详解
    DOS批处理中%cd%和%~dp0的区别
    SetACL 使用方法详细参数中文解析
    Lazarus 1.6 增加了新的窗体编辑器——Sparta_DockedFormEditor.ipk
    Lazarus 1.44升级到1.6 UTF8处理发生变化了
  • 原文地址:https://www.cnblogs.com/yanmk/p/9194769.html
Copyright © 2011-2022 走看看