我需要用Python编写一个程序,给定一个整数作为输入,计算从1开始一直到无穷大的连续行自然数中的数字(例如12345678910111213141516171819202122等...)例如,如果我们输入17它计算该行中的第 17 位数字,即 3。
我已经编写了一个程序,可以计算到第 189 位数字,但我需要将其计算为非常大的数字(直到位置 2**31-1)
def digit_finder():
if pos < 10: #Position is equal to digit.
digit=pos
return(digit)
elif pos >= 10 en pos < 189: #Number between 10 and 99.
number=(pos-9)
if pos%2==0:
new_number=(10+(number//2))
digit=(new_number//10)
return digit
else:
new_number=(9+(number//2))
digit=(new_number-((new_number//10)*10))
return digit
我不知道如何继续获得更大的数字。 请帮忙!
最佳答案
一种方法是将每个数字转换为字符串并将它们全部链接到一个无尽的生成器中。然后,您从一开始就忽略一定数量的字符,然后采用下一个......,例如:
from itertools import chain, count, islice
def digit_finder(n):
digits = chain.from_iterable(str(i) for i in count(1))
return int(next(islice(digits, n - 1, None)))
print(digit_finder(17))
关于python - 用 Python 解方程。计算第n位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19391152/