编写一个 python 程序来反转给定的数字

write a python program to reverse the given numbers

输入=12345 输出=54321

写数字反转的程序

n=int(input("Enter number :"))
rev=0
while(n>0):
    dig = n%10
    rev=rev*10+dig
    n=n//10
print("The reverse of the number:" ,rev)

可以解释一下为什么打印 54321

这应该有效

number = int(input("Enter a number: "))
rev = ''
 
while number > 0:
    last_digit = number % 10 #The remainder when it's divided by 10 will always be the last digit
    rev = rev + str(last_digit)
    number = number // 10
 
print("Reversed : ", rev)

让 n = 12345 ,其中 12345 是给定的输入。

rev = 0
Now in the first iteration of the while loop n > 0
dig = remainder of n divided by 10, So it is = 5
rev = rev(0) * 10 + dig(5) = 5
n = n // 10 = 1234

在第二次迭代中,n = 1234 > 0

rev = 5
dig = remainder of n divided by 10, So it is = 4
rev = rev(5) * 10 + dig(4) = 54
n = n // 10 = 123

在第三次迭代中,n = 123 > 0

rev = 54
dig = remainder of n divided by 10, So it is = 3
rev = rev(54) * 10 + dig(3) = 543
n = n // 10 = 12

在第四次迭代中,n = 12 > 0

rev = 543
dig = remainder of n divided by 10, So it is = 2
rev = rev(543) * 10 + dig(2) = 5432
n = n // 10 = 1

在第五次迭代中,n = 1 > 0

rev = 5432
dig = remainder of n divided by 10, So it is = 1
rev = rev(5432) * 10 + dig(1) = 54321
n = n // 10 = 0

现在在 while 循环的第六次迭代中 n = 0 所以它不大于 0 所以循环将中断并且你得到 rev = 54321

其实很简单

第一次迭代

  1. 好吧,你首先得到 10 的百分比,这基本上是最后一个数字(残差)dig = 5,
  2. 比你将这个添加到 rev*10(在第一次迭代 0 中)+ dig = 5,
  3. 然后你将整个数字除以 10(删除最后一个数字)n = 1234

第二次迭代

  1. 挖掘 = 4
  2. 转=5*10 + 4 = 54
  3. n = 123

第三次迭代

  1. 挖掘 = 3
  2. rev = 540 + 3 = 543
  3. n = 12

...

然而,有更简单的方法来做到这一点,例如。

如果你输入的是字符串,那么你只需要反转它

input = "12345"
output = input[::-1]

如果输入是数字 (int, float) 则必须将其转换为字符串

input = 12345
output = str(input)[::-1]

然后转换回来

int(output)

请参阅其他答案以获得很好的解释。在这里我为原问题添加了 2 个更简单的解决方案——如何反转数字:

# For example, 12345:
num = input("Enter number: ")

# fastest and shortest:
rev = num[::-1]

# or (slower and longer)
rev = "".join(reversed(num))

print(f"The reverse of the number: {rev}")
# The reverse of the number: 54321

这样就简单多了

inp = input("Enter the number")
list1 = [numbers for numbers in inp]
list2 = [reversed_numbers for reversed_numbers in list1[::-1]]
print("".join(list2))

您可以在 python 中迭代一个字符串,并且您将迭代每个字符

好了:

a = input("Enter : ")
x = [num for num in a]  # Getting the individual digits
b = reversed(x)         # reversed() is a built in function
print("".join(b))