对于 necro-threading,我感到非常抱歉,但我想提供一个解决方案,而不会将整数转换为字符串。此外,我想使用更多类似计算机的思维方式工作,这就是为什么 Chris Mueller 的回答对我来说不够好。
那么,废话不多说,
import math
def count_number(number):
counter = 0
counter_number = number
while counter_number > 0:
counter_number //= 10
counter += 1
return counter
def digit_selector(number, selected_digit, total):
total_counter = total
calculated_select = total_counter - selected_digit
number_selected = int(number / math.pow(10, calculated_select))
while number_selected > 10:
number_selected -= 10
return number_selected
def main():
x = 1548731588
total_digits = count_number(x)
digit_2 = digit_selector(x, 2, total_digits)
return print(digit_2)
if __name__ == '__main__':
main()
将打印:
5
希望其他人可能需要这种特定类型的代码。希望对此也有反馈!
这应该找到整数中的任何数字。
缺陷:
效果很好,但是如果您将其用于长数字,则将花费越来越多的时间。我认为可以查看是否有数千个等,然后从 number_selected 中减去这些,但这可能是另一个时间;)
用法:
您需要从 1 到 21 的每一行。然后你可以调用 first count_number 让它计算你的整数。
x = 1548731588
total_digits = count_number(x)
然后读取/使用digit_selector函数如下:
digit_selector('在此处插入你的整数', '你想要哪个数字?(从最左边的数字开始为1)', '一共有多少个数字?')
如果我们有 1234567890,我们需要选择 4,即从左数第 4 位,所以我们输入“4”。
由于使用了 total_digits,我们知道有多少位数。所以这很容易。
希望能解释一切!
韩
PS:特别感谢 CodeVsColor 提供 count_number 函数。我使用此链接:https://www.codevscolor.com/count-number-digits-number-python 帮助我使 digit_selector 工作。