Without converting the number to a string:

def reverse_number(n):
    r = 0
    while n > 0:
        r *= 10
        r += n % 10
        n /= 10
    return r

print(reverse_number(123))
Answer from Alberto on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › can anyone explain how to reverse a integer number?
r/learnpython on Reddit: Can anyone explain how to reverse a integer number?
February 1, 2022 -

Sorry if that sound like stupid, I'm just a newbie to programming

At first I thought it was easy and started writing code and I find myself with bunch of errors.

Then I came up with this:

number = 12345
reverse = str(number)[::-1]
print(reverse)

It's just cheating you can say, I converted integer into string and made that string reverse.

After a while I thought, I'm just stupid to code like this but then later I googled and I found this solution which is more complicated to understand:

number = 12345

reverse = 0
while number > 0:
  last_digit = number % 10
  reverse = reverse * 10 + last_digit
  number = number // 10

print(reverse)

Can anyone please explain what's going on here?

Discussions

Convert to binary - functions
No need for that, Python already has string formatting for this conversion. Input: f'{6:08b}' # In other words, "take this number, convert it to binary and pad eight zeroes to the left" Output: '00000110' More on reddit.com
🌐 r/learnpython
7
5
April 25, 2022
Can anyone explain how to reverse a integer number?
That's hardly cheating, and is now I'd do it unless that method was explicitly forbidden (I had that once). Your div/mod way is more complicated, and in my experience, likely doesn't have much in the way of noticeable performance advantages anyway. Abusing strings is often a good solution surprisingly (but consider each case individually). More on reddit.com
🌐 r/learnpython
26
38
February 2, 2022
You can use [~i] for reverse indexing rather than [-i-1]
PEP 20: "cryptic is better than clear" More on reddit.com
🌐 r/Python
112
308
March 2, 2017
Endianness conversion of hex values in Python 2.x vs 3.x and ELI5 why bytes are used?
The decode method converts the string of hex digits into an actual sequence of bytes. You can't slice the string directly because in the string each character represents only 4 bits, but you want to reverse each 8 bit group (byte). Try printing the reprs of the intermediate values to understand what's going on. In python 3 they removed the ability to decode strings using a method because that operation very rarely makes sense and caused more problem that it solved. You can still use codecs on strings, it's just a little more roundabout now. import codecs x = 'abcd' d = codecs.encode(codecs.decode(x, 'hex')[::-1], 'hex').decode() This kind of stuff is easier if you just realise that you're working with bytes in the first place, rather than trying to keep hold of a string of digits. More on reddit.com
🌐 r/learnpython
5
0
November 13, 2014
People also ask

Can I reverse a number using loops in Python?
Yes, you can reverse a number by using a while loop. Divide the number by 10 to extract digits and multiply the result by 10 to rebuild the reversed number step by step.
🌐
wscubetech.com
wscubetech.com › resources › python › programs › reverse-number
Reverse a Number in Python (5 Different Ways)
How can I reverse a number in Python using a string?
You can convert the number to a string with str(), reverse it using slicing ([::-1]), and then turn it back into an integer using int().
🌐
wscubetech.com
wscubetech.com › resources › python › programs › reverse-number
Reverse a Number in Python (5 Different Ways)
What are the benefits of using recursion to reverse a number in Python?
Recursion simplifies the process by repeatedly calling the function to break down the number and reverse it until it’s done.
🌐
wscubetech.com
wscubetech.com › resources › python › programs › reverse-number
Reverse a Number in Python (5 Different Ways)
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-program-to-reverse-a-number
Python Program to Reverse a Number - GeeksforGeeks
November 18, 2025 - Reversing means rearranging the ... any digit. For Example: ... Let's explore different methods to reverse a number in Python. This method reverses the number by converting it to a string, slicing it in reverse order and converting it back to an integer....
🌐
Programiz
programiz.com › python-programming › examples › reverse-a-number
Python Program to Reverse a Number
To understand this example, you should have the knowledge of the following Python programming topics: ... num = 1234 reversed_num = 0 while num != 0: digit = num % 10 reversed_num = reversed_num * 10 + digit num //= 10 print("Reversed Number: " + str(reversed_num)) ... First, the remainder of the num divided by 10 is stored in the variable digit.
🌐
Medium
medium.com › @reza.shokrzad › reverse-integer-problem-exploring-simple-and-optimized-python-solutions-8e6d6818c2bd
Reverse Integer Problem: Exploring Simple and Optimized Python Solutions | by Reza Shokrzad | Medium
June 14, 2024 - def reverse_integer_simple(x): ... and handles the reversal purely with arithmetic operations: Initialize a variable to hold the reversed number....
🌐
PYnative
pynative.com › home › python › programs and examples › python programs to reverse an integer number
Python Programs to Reverse an Integer Number
March 31, 2025 - num = 123456 reversed_int = 0 negative ... use the same mathematical formula discussed in the above approach, where we extract digits one by one and construct the reversed number in each recursive call....
Find elsewhere
🌐
Code and Debug
codeanddebug.in › home › data structures & algorithms › leetcode #7 : reverse integer python program explained
Leetcode #7 : Reverse Integer Python Program Explained
July 7, 2025 - In this article, we’ll guide you ... “x”. Purpose: The function reverse is designed to take an integer “x”, reverse its digits, and return the reversed integer....
🌐
datagy
datagy.io › home › python posts › python: reverse a number (3 easy ways)
Python: Reverse a Number (3 Easy Ways) • datagy
December 20, 2022 - We multiply our reversed number by 10 and add our digit · Finally, we return the floored result of our number divided by 10 (this essentially removes the number on the right) This process is repeated until our original number is equal to zero · It’s important to note, this approach only works for integers and will not work for floats. In the next section, you’ll learn how to use Python string indexing to reverse a number.
🌐
NxtWave
ccbp.in › blog › articles › reverse-a-number-in-python
Reverse a Number in Python: Methods & Best Practices
On the other hand, mathematical operations provide a more algorithmic approach to manipulating digits instead of converting the number to a string. In addition, Python has built-in options like the reversed() function or the use of list slicing, ...
🌐
WsCube Tech
wscubetech.com › resources › python › programs › reverse-number
Reverse a Number in Python (5 Different Ways)
October 29, 2025 - Explore 5 different ways to reverse a number in Python. Get step-by-step code examples, outputs, and clear explanations to enhance your understanding.
🌐
CodeRivers
coderivers.org › blog › reversing-integer-python
Reversing an Integer in Python: Concepts, Usage, and Best Practices - CodeRivers
February 22, 2026 - def reverse_integer_with_error_handling(num): try: if not isinstance(num, int): raise ValueError("Input must be an integer") # Use one of the reversal methods here return reverse_integer_math_method(num) except ValueError as ve: print(f"Error: {ve}") # Test the function input_value = "not an integer" result = reverse_integer_with_error_handling(input_value) Boundary Conditions: Consider boundary conditions such as reversing 0, the smallest and largest possible integers. In Python, the integer type has arbitrary precision, but in some cases, you may need to handle specific limitations. For example, if you are working in a system with a fixed-width integer representation, you need to ensure that the reversed number does not cause an overflow.
🌐
Javatpoint
javatpoint.com › how-to-reverse-a-number-in-python
How to reverse a number in Python - Javatpoint
How to reverse a number in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, basics, data types, operators, etc.
🌐
Replit
replit.com › discover › how-to-reverse-a-number-in-python
How to reverse a number in Python
February 6, 2026 - Build and deploy software collaboratively with the power of AI without spending a second on setup.
🌐
Scaler
scaler.com › home › topics › reverse a number in python
Reverse a Number in Python - Scaler Topics
June 21, 2024 - In this way, the new string so ... Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L. ... We use the python reversed() function to reverse a number by this method....
🌐
PREP INSTA
prepinsta.com › home › python program › reverse a number in python
Reverse of a number in Python | PrepInsta​
July 29, 2023 - Using the formula reverse = ( reverse * 10 ) + remainder , we keep changing the reverse value. Break down the Nunber using divide operator. Print the reverse variable. Let’s implement the above mentioned Logic in Python Language.
🌐
w3resource
w3resource.com › python-exercises › challenges › 1 › python-challenges-1-exercise-18.php
Python: Reverse the digits of an integer - w3resource
Write a Python program to reverse the digits of an integer. ... def reverse_integer(x): sign = -1 if x < 0 else 1 x *= sign # Remove leading zero in the reversed integer while x: if x % 10 == 0: x /= 10 else: break # string manipulation x = str(x) lst = list(x) # list('234') returns ['2', '3', '4'] lst.reverse() x = "".join(lst) x = int(x) return sign*x print(reverse_integer(234)) print(reverse_integer(-234))
🌐
Python Forum
python-forum.io › thread-32496.html
Reverse Function in Python
Hi everyone i am beginner in python i am facing with this exercice can anyone explained how to write this in Python : Exercice : ----------------------------- Write a function reverse that receives an integer n as a parameter and returns that in...
🌐
Tutorial Gateway
tutorialgateway.org › python-program-to-reverse-a-number
Python Program to Reverse a Number
April 7, 2025 - To reverse a number, first, you must find the last digit in a number. Next, add it to the first position of the other variable, then remove that last digit from the original number.
🌐
Edureka
edureka.co › blog › how-to-reverse-a-number
How to reverse a number in Python | Python Program Explained | Edureka
September 24, 2019 - It’s simple! You can write a Python program which takes input number and reverse the same. The value of an integer is stored in a variable which is checked using a condition and then each digit of the number is stored in another variable, which will print the reversed number.
🌐
C# Corner
c-sharpcorner.com › code › 3430 › reverse-number-in-python.aspx
Reverse Number In Python
June 8, 2016 - reverse.zip · # Python Program to Reverse a Number using While loop · Number = int(input("Please Enter any Number: ")) Reverse = 0 · while(Number > 0): Reminder = Number  · Reverse = (Reverse *10) + Reminder · Number = Number //10 · print("\n ...