defreverse1(x): """ :type x: int :rtype: int """ if x == 0: return0 y = "" r = 0 a = str(x) length = len(a) for i in range(length): index = length - 1 - i ifnot y and a[index] == "0": continue y += a[index] if y[-1] == "-": r = -int(y[0:-1]) if r < MIN: return0 return r r = int(y) if r > MAX: return0 return r
defreverse2(x): """ 使用取余的方式,弹出 x 的最后一位,并推到 r 的后面,并如此往复,直到 x = 0 :type x: int :rtype: int """ r = 0 while x != 0: chu = 10 if x < 0: # 根据整数的正负,使用相应的取余除数 chu = -10 pre = x % chu # 弹出 x 的最后一位 x = (x - pre) // 10# 取余完毕后,整数减去一位 if r > MAX_R or (r == MAX_R and pre == 7): # MAX_R = 2147483640 # 此处防止后续推入 pre 时,整数溢出 return0 if r < MIN_R or (r == MIN_R and pre == -8): # MIN_R = -2147483648 # 此处防止后续推入 pre 时,整数溢出 return0 r = r * 10 + pre # 将弹出的最后一位,推到 r 的后面 return r
defprint_func_run_time(count, func, **kw): b = time.clock() for i in range(count): func(**kw) print(func.__name__, 'run {} times used {}s'.format(count, time.clock() -b ))