本文首發(fā)于我的個(gè)人博客Suixin’s Blog
原文: https://suixinblog.cn/2019/03/target-offer-int-power.html 作者: Suixin
題目描述
給定一個(gè)double類型的浮點(diǎn)數(shù)base和int類型的整數(shù)exponent酸员。求base的exponent次方。
解題思路
使用遞歸的方法,將整數(shù)次冪除2宙址,底數(shù)變?yōu)樵瓉?lái)的平方独撇。不能整除的向下取整厘灼,再多乘一個(gè)底數(shù)义图。指數(shù)為負(fù)時(shí)將底數(shù)取倒數(shù)艇棕,指數(shù)變正蝌戒。
特殊輸入測(cè)試:底數(shù)為0,指數(shù)為負(fù)的無(wú)效輸入沼琉;指數(shù)為負(fù)北苟;
代碼
Python(2.7.3)
投機(jī)取巧法
這道題目本來(lái)是出給C#/C++
的答題者,考察代碼的完整性打瘪,但奈何Python面向?qū)ο筇珡?qiáng)大……呸友鼻!以題解題還有理了……
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
return base ** exponent
運(yùn)行時(shí)間:23ms
占用內(nèi)存:5624k
正常遞歸解法
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if base == 0 and exponent < 0:
raise ValueError("Please enter valid numbers!")
elif exponent == 0:
return 1
elif exponent == 1:
return base
elif exponent < 0:
base = 1 / base
exponent = -exponent
if exponent % 2 == 0:
return self.Power(base * base, exponent / 2)
else:
return self.Power(base * base, exponent // 2) * base
運(yùn)行時(shí)間:31ms
占用內(nèi)存:5712k