Find power
Last updated
Last updated
2.00000,38.00000# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
#
# write code here
# base*base in iteration = base^1, base^2, base^4, base^8
#... = base^(2^0 + 2^1 + 2^2 + 2^3 + ....2^n)
# res = x1* base^1 * x2*base^2 * x3*base^4* ...
# xi = 1 or 0 bit depending on exponent 的bit 二进制位数
#用于倒数
sign = False
if exponent <0:
sign = True
exponent *= -1
res = 1
# base^exp = base ^ (2^1 + 2^2 +.. 2^n)
# = base^(2^1) * base^(2^2) * ... *base^(2^n)
# 如果对于的base^(2^i) 是存在,就把那个base 乘上去 res里面
while exponent >0:
if exponent & 1 ==1:
res = res * base
exponent >>= 1
# 计算每个base^(2^i)
base *= base
return 1/res if sign else res