2021-01-26 leetcode 1018. 可被 5 整
2021-01-26 本文已影响0人
fanchuang
简单的题目,绕了大圈子,希望下次长记性。
# 很简单的一道题
"""
执行结果:
通过显示详情执行用时:1304 ms, 在所有 Python3 提交中击败了5.15%的用户
内存消耗:15.7 MB, 在所有 Python3 提交中击败了41.14%的用户
效果貌似很差劲啊。
这道题主要的时间消耗在于,如果数组A比较长的时候, 那么A[:n]所表示整数会特别大,所以需要取模。
即, 如果 10000005 % 5 == 0, 那么就让 10000005 = 0
# 这里我也是绕了一个大圈子啊, 去百度百科查看取模运算的详情。目的也是在于深刻地理解问题。
取模运算
虽然很多数论教材上对模运算都有一定的介绍,但多数都是以纯理论为主,对于模运算在程序设计中的应用涉及不多。
python -7 % 4 = 1
取模定律 (a * b) % p = (a % p * b % p) % p
取模定律有很多条, see:
https://baike.baidu.com/item/%E5%8F%96%E6%A8%A1%E8%BF%90%E7%AE%97/10739384?fr=aladdin
"""
import random
from my_timer import timer
# g = []
# for m in range(10000):
# g.append(random.choice([0,1]))
# print(g)
@timer
def solution():
ret = []
temp = "0"
for x in A:
temp += str(x)
if int(temp, base=2) % 5 == 0:
ret.append(True)
temp = "0"
else:
ret.append(False)
print(ret)
# before 0.0690622329711914 seconds on: solution
# after 0.00800776481628418 seconds on: solution
if __name__ == '__main__':
solution()