Python Program to Reverse a Number Using While Loop
num % 10, adding it to a reversed number multiplied by 10, and then removing the last digit from the original number with num //= 10 until the number becomes zero.Examples
How to Think About It
num % 10, add it to the reversed number after shifting the reversed number left by one digit (multiply by 10), and then remove the last digit from the original number using num //= 10.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 the number 1234 through the code to see how it reverses.
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 is now 0, exit loop
| 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, which we add to the reversed number.
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 remove the last digit from the original number and continue the loop.
Alternative Approaches
num = input("Enter a number: ") reversed_num = int(num[::-1]) print("Reversed number:", 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 the time complexity is O(d), where d is the number of digits.
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The while loop method is efficient and uses constant space. String conversion is simpler but uses extra space for the string. Recursion uses more stack space and is less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| While loop | O(d) | O(1) | Memory-efficient, beginner-friendly |
| String conversion | O(d) | O(d) | Quick and simple for small inputs |
| Recursion | O(d) | O(d) | Elegant but uses more memory |
// to remove digits when working with numbers in loops.