面試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