Reverse a number - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Reverse a number (/thread-26347.html) |
Reverse a number - kLgG40 - Apr-29-2020 Hi! So for my homework assignment, we have to reverse a four digit number. # Python Class 2402 # Lesson 2 Problem 6 # Author: KitKatKarateIlluminati (491160) FourDigit = int(input("Please enter a four digit number: ")) First = FourDigit % 10 Second = ((FourDigit % 100) - First)/10 Third = (FourDigit - (Second * 10 + First))/100 Fourth = (FourDigit - (First + Second * 10 + Third * 100))/1000 Reverse = Fourth + Third * 10 + Second * 100 + First * 1000 print(Reverse)Can you guys please tell me why this is wrong? Thanks in advance! RE: Reverse a number - perfringo - Apr-29-2020 I think that the easiest way would be to convert int to a string, reverse it, construct a new string and convert it back to int. As you actually have a string as user input then you can skip conversion. Doesn't matter how many digits: >>> num = 12345 >>> int(''.join((reversed(str(num))))) 54321If you want to calculate, maybe have a look at builtin divmod() RE: Reverse a number - anbu23 - Apr-29-2020 First = FourDigit % 10 Second = ((FourDigit - First) % 100) /10 Third = ((FourDigit - (Second * 10 + First)) /100)%10 Fourth = (FourDigit - (First + Second * 10 + Third * 100))/1000Or >>> FourDigit='1234' >>> FourDigit[::-1] '4321' RE: Reverse a number - DeaD_EyE - Apr-29-2020 Interesting operators and functions you should read more about:
I removed my solution. You should do it mathematically. RE: Reverse a number - pyzyx3qwerty - Apr-29-2020 You can do this : num1 = input("Please enter a 4-digit number : ") num2 = num1[::-1] print(num2)And output :
|