第一想法就是用函数pow或者直接写表达式:
class Solution:
def Power(self, base, exponent):
# write code here
return base**exponent
or
def Power(self, base, exponent):
# write code here
return base**exponent
or
classSolution:
def Power(self, base, exponent):
# write code here
return pow(base, exponent)
或者你自己迭代一下其实也可以, 就是最简单的方法,不过要注意exponent为负值的时候幂函数的表达式不一样 # -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if exponent == 0:
return 1
if base == 0|1:
return base
if exponent < 0:
base = 1/base
exponent = -exponent
res = 1
for i in range(exponent):
res = res * base
return res
class Solution:
def Power(self, base, exponent):
# write code here
if exponent == 0:
return 1
if base == 0|1:
return base
if exponent < 0:
base = 1/base
exponent = -exponent
res = 1
for i in range(exponent):
res = res * base
return res