16. 数值的整数次方
数值的整数次方
http://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00
- 要根据exponent是正数还是负数进行讨论,另外要考虑base=0 的情况,利用递归来实现O(logn)的时间
class Solution:
def Power(self, base, exponent):
# write code here
if base == 0:return 0
if exponent >= 0: return self.PowerWithUnsignedExponent(base, exponent)
if exponent < 0: return 1.0/self.PowerWithUnsignedExponent(base, (-1)*exponent)
def PowerWithUnsignedExponent(self, base, exponent):
if exponent == 0:
return 1
if exponent == 1:
return base
res = self.PowerWithUnsignedExponent(base, exponent//2)
res *= res
if exponent % 2 == 1:
res *= base
return res
- 优化代码,将Exponent右移一位相当于除以2,将Exponent与1做与运算,得1为奇数,得0为偶数
res = self.PowerWithUnsignedExponent(base, exponent>>1)
res *= res
if exponent & 0x1 == 1:
res *= base
return res