• 剑指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 全文索引分词
    Json官方介绍
    SQL Try Catch(转载http://www.cnblogs.com/jimmyray/archive/2011/08/02/2125069.html)
    SQL函数记录
    SQL事务处理代码(SQL Server 2000 & 2005)
    SQL通用分页存储过程
    [导入]SoapExtension 1.0 的问题与解决
    BugTracker.NET 汉化手札
    [导入]我对J2EE和.NET的一点理解
    PostgreSQL 8.0.2 应用报告
  • 原文地址:https://www.cnblogs.com/yanmk/p/9194769.html
Copyright © 2020-2023  润新知