Python Program to Reverse a Number with Output and Explanation
% 10 and building the reversed number by multiplying the current reversed number by 10 and adding the digit, like this: while num > 0: digit = num % 10; reversed_num = reversed_num * 10 + digit; num //= 10.Examples
How to Think About It
%. Then, build a new number by shifting the current reversed number left (multiply by 10) and adding the peeled digit. Repeat until the original number is fully processed.Algorithm
Code
num = int(input("Enter a number: ")) reversed_num = 0 while num > 0: digit = num % 10 reversed_num = reversed_num * 10 + digit num //= 10 print("Reversed number:", reversed_num)
Dry Run
Let's trace reversing 1234 through the code
Initial values
num = 1234, reversed_num = 0
First loop iteration
digit = 1234 % 10 = 4; reversed_num = 0 * 10 + 4 = 4; num = 1234 // 10 = 123
Second loop iteration
digit = 123 % 10 = 3; reversed_num = 4 * 10 + 3 = 43; num = 123 // 10 = 12
Third loop iteration
digit = 12 % 10 = 2; reversed_num = 43 * 10 + 2 = 432; num = 12 // 10 = 1
Fourth loop iteration
digit = 1 % 10 = 1; reversed_num = 432 * 10 + 1 = 4321; num = 1 // 10 = 0
Loop ends
num = 0, reversed_num = 4321
| num | digit | reversed_num |
|---|---|---|
| 1234 | 4 | 4 |
| 123 | 3 | 43 |
| 12 | 2 | 432 |
| 1 | 1 | 4321 |
Why This Works
Step 1: Extract last digit
Using num % 10 gets the last digit of the number, like peeling one digit off.
Step 2: Build reversed number
Multiply the current reversed number by 10 to shift digits left, then add the extracted digit to append it.
Step 3: Remove last digit
Use integer division num //= 10 to drop the last digit from the original number and continue.
Alternative Approaches
num = input("Enter a number: ") reversed_num = num[::-1] print("Reversed number:", int(reversed_num))
def reverse_num(num, rev=0): if num == 0: return rev return reverse_num(num // 10, rev * 10 + num % 10) num = int(input("Enter a number: ")) print("Reversed number:", reverse_num(num))
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time grows linearly with the number of digits, O(d).
Space Complexity
Only a few variables are used, so space is constant, O(1).
Which Approach is Fastest?
The arithmetic loop method is fastest and uses constant space. String conversion is simpler but uses extra memory for strings. Recursion is elegant but less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic loop | O(d) | O(1) | Efficient and memory-friendly |
| String conversion | O(d) | O(d) | Simple code, small numbers |
| Recursive | O(d) | O(d) | Elegant but limited by recursion depth |
// to remove digits and modulus % to extract digits when reversing numbers.