Reputation: 13
Input=12345 output=54321
Program to write a reverse of numbers
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)
Can some explain why this print 54321
Upvotes: 0
Views: 5320
Reputation: 53
You can iterate a string in python, and you'll be iterating by each character
There you go:
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))
Upvotes: 2
Reputation: 36
This is much simpler
inp = input("Enter the number")
list1 = [numbers for numbers in inp]
list2 = [reversed_numbers for reversed_numbers in list1[::-1]]
print("".join(list2))
Upvotes: 1
Reputation: 12337
See other answer for great explanations. Here I add 2 simpler solutions to the original problem - how to reverse a number:
# 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
Upvotes: 0
Reputation: 323
It's actualy pretty simple
1st iteration
2nd iteration
3rd iteration
...
However there is much easier way how to do this eg.
If your input is string so you just need to reverse it
input = "12345"
output = input[::-1]
If input is number (int, float) than you have to convert it to string
input = 12345
output = str(input)[::-1]
And convert back
int(output)
Upvotes: 0
Reputation: 190
Let, n = 12345 , where 12345 is the given input.
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
In the second iteration n = 1234 which is > 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
In the third iteration n = 123 which is > 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
In the fourth iteration n = 12 which is > 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
In the fifth iteration n = 1 which is > 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
Now in the sixth iteration of the while loop n = 0 so it is not greater than 0 so loop will break and you got rev = 54321
Upvotes: 0
Reputation: 863
This should work
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)
Upvotes: 0