Implement pow(x, n).
Subscribe to see which companies asked this question
最开始肯定是用x ** n,当然这个太无赖。
开始自己实现,首先想的是,每次平方,但是遇到2^k - 1这种,就等于没有量级上的优化,肯定是超时了。
提示是二分法,那就增加一个字典,来存这个数的2 的指数次幂,比如1.00001举例子,字典长成这个样子
[(131072, 492152.88234684995), (65536, 701.5360877010177), (32768, 26.48652653144647), (16384, 5.146506245157628), (8192, 2.268591246822051), (4096, 1.5061843336132703), (2048, 1.2272670180581202), (1024, 1.1078208420399573), (512, 1.0525306846073217), (256, 1.025929181087721), (128, 1.0128816224454469), (64, 1.0064202017276118), (32, 1.003204964963597), (16, 1.0016012005601815), (8, 1.0008002800560067), (4, 1.000400060004), (2, 1.00020001), (1, 1.0001)]
然后对每个剩余没算的幂,逐个算
class Solution(object):
def myPow(self, x, n):
if n == 0:
return 1
minus = 0
if n < 0:
minus = 1
n = -n
p = 1
res = x
l = {}
if x == 1:
return 1
if n == 2:
res = x * x
if minus == 1:
res = 1/res
return res
while (p << 1) < n:
l[p] = res
res *= res
p = p << 1
l = sorted(l.iteritems(),key = lambda d:d[0], reverse = True)
#l = dict(l)
#print p,res,l
while p < n:
for i in l:
if i[0] > n- p:
del l[0]
continue
#print i,l,'\n'
res *= i[1]
p += i[0]
break
if minus == 1:
res = 1/res
return res
#return x**n