In this tutorial -:

Understanding the Problem
To reverse a number, we need to rearrange its digits in the opposite order. For example, if the number is 12345, its reverse will be 54321. We have to do this in the most optimized way possible.
Developing the Algorithm
To reverse a number with traditional way, we can follow these steps:
- Initialize reversed_number to 0.
- Iterate until the number is greater than 0:
- Calculate the remainder by performing modulo division of number by 10.
- Update reversed_number by multiplying it by 10 and adding the remainder.
- Divide number by 10 using floor division (//) to remove the last digit.
- Return reversed_number as the reversed number.
Writing the Python Code
def reverse_number(number):
reversed_number = 0
while number > 0:
remainder = number % 10
reversed_number = (reversed_number * 10) + remainder
number //= 10
return reversed_number
# Test the function
number = 12345
reversed_number = reverse_number(number)
print("Original number:", number)
print("Reversed number:", reversed_number)
O/P
Original number: 12345
Reversed number: 54321
Time Complexity: O(N)
Code Explanation
1. We define a function reverse_number that takes the number as an argument and returns the reversed number.
2. We initialize reversed_number to 0, which will hold the reversed number.
3. Using a while loop, we iterate until number becomes 0.
4. In each iteration, we calculate the remainder by performing modulo division of number by 10.
5. We update reversed_number by multiplying it by 10 and adding the remainder.
6. We then divide number by 10 using floor division (//) to remove the last digit.
7. The loop continues until number becomes 0.
Finally, we return reversed_number as the reversed number.
Dry Run the Code
Let’s do a dry run of the code for number = 12345:
Iteration 1:
number is 12345.
remainder is 5.
reversed_number is 5.
number becomes 1234.
Iteration 2:
number is 1234.
remainder is 4.
reversed_number is (5 * 10) + 4 = 54.
number becomes 123.
Iteration 3:
number is 123.
remainder is 3.
reversed_number is (54 * 10) + 3 = 543.
number becomes 12.
Iteration 4:
number is 12.
remainder is 2.
reversed_number is (543 * 10) + 2 = 5432.
number becomes 1.
Iteration 5:
number is 1.
remainder is 1.
reversed_number is (5432 * 10) + 1 = 54321.
number becomes 0.
The loop ends, and the code prints “Original number: 12345” and “Reversed number: 54321”.
This traditional approach iteratively extracts the last digit from the number and builds the reversed number by multiplying the current reversed number by 10 and adding the extracted digit.
