Ruby Program to Reverse a Number with Output and Explanation
% 10 and building the reversed number by multiplying the result by 10 and adding the digit, like this: while num > 0; digit = num % 10; reversed = reversed * 10 + digit; num /= 10; end.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
puts "Enter a number:" num = gets.to_i reversed = 0 while num > 0 digit = num % 10 reversed = reversed * 10 + digit num /= 10 end puts "Reversed number: #{reversed}"
Dry Run
Let's trace the number 123 through the code to see how it reverses.
Initial values
num = 123, reversed = 0
First iteration
digit = 123 % 10 = 3; reversed = 0 * 10 + 3 = 3; num = 123 / 10 = 12
Second iteration
digit = 12 % 10 = 2; reversed = 3 * 10 + 2 = 32; num = 12 / 10 = 1
Third iteration
digit = 1 % 10 = 1; reversed = 32 * 10 + 1 = 321; num = 1 / 10 = 0
Loop ends
num is now 0, loop stops; reversed number is 321
| num | digit | reversed |
|---|---|---|
| 123 | 3 | 3 |
| 12 | 2 | 32 |
| 1 | 1 | 321 |
Why This Works
Step 1: Extract last digit
Using num % 10 gets the last digit of the number.
Step 2: Build reversed number
Multiply the current reversed number by 10 to shift digits left, then add the extracted digit.
Step 3: Remove last digit
Divide the original number by 10 using integer division to remove the last digit.
Alternative Approaches
puts "Enter a number:" num = gets.chomp reversed = num.reverse puts "Reversed number: #{reversed.to_i}"
def reverse_num(num, rev=0) return rev if num == 0 reverse_num(num / 10, rev * 10 + num % 10) end puts "Enter a number:" num = gets.to_i puts "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 regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The arithmetic method is fastest and uses constant space. String conversion is simpler but slower and uses extra space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic loop | O(d) | O(1) | Performance and memory efficiency |
| String conversion | O(d) | O(d) | Simplicity and quick coding |
| Recursive method | O(d) | O(d) | Elegant code but limited by recursion depth |