获取长字符串的最后n位数

2024-04-19 01:02:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序要求用户输入一个电源和他们想要的数字。并查找最后一个将2的多个数字提升到用户输入的幂次方的数字。你知道吗

我的代码是这样的。我只是python的初学者。我没有得到想要的结果。你知道吗

temp = int(input('Enter the power of the number: '))
temp2 = int(input('Enter the no.of digits you want: '))
temp3 = (2 ** temp) // temp2
temp4 = (temp3 % 100)
print('The last that many digits of the number raised to the power is is:',temp4)

Tags: ofthe用户numberinputis数字temp
1条回答
网友
1楼 · 发布于 2024-04-19 01:02:54

我假设你在找这样的东西:

功率:8

数字:2

2^8=256个

最后两位=56

为此,您的代码如下所示:

power = int(input('two to the power of '))
digits = int(input('last how many digits? '))

num = 2 ** power # calculate power
num = num % (10 ** digits) # get remainder of division by power of 10
print(num)

另一种方法是:

power = int(input('two to the power of '))
digits = int(input('last how many digits? '))

num = 2 ** power # calculate power
num = str(num) # convert with string to work with
num = num[-digits:] # get last n digits
num = int(num)
print(num)

相关问题 更多 >