最基础的解法,就是循环地乘以base,这里有一个问题,当指数为0和负数时候的处理。
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
ans = 1
if exponent > 0:
for i in range(exponent):
ans *= base
elif exponent == 0:
return 1
else:
for i in range(-1*exponent):
ans *= base
ans = 1 / ans
return ans
书中给出的优化的算法:
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if exponent == 0:
return 1
if exponent == 1:
return base
flag = False
if exponent < 0:
flag = True
exponent *= -1
result = self.Power(base, exponent >> 1)
result *= result
if exponent & 0x1 == 1:
result *= base
if flag == True:
return 1/result
return result