题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
思路:一个函数搞定
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
return pow(base, exponent)
一种高效的解法:递归 O(logn)时间复杂度
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if base == 0:
return False
if exponent<0:
result = self.UnsignedPower(base, abs(exponent))
result = 1/result
else:
result = self.UnsignedPower(base, exponent)
return result
def UnsignedPower(self, base, exponent):
if exponent == 0:
return 1
if exponent == 1:
return base
result = self.Power(base, exponent>>1)
result = result*result
if (exponent//2==1):
result = result*base
return result