PHP Program to Reverse a Number with Output and Explanation
% 10, building the reversed number by multiplying the current reversed number by 10 and adding the digit, and removing the last digit from the original number using / 10. For example: $reversed = 0; while ($num > 0) { $reversed = $reversed * 10 + $num % 10; $num = (int)($num / 10); }Examples
How to Think About It
% to get the last digit, then add it to the reversed number after shifting the reversed number left by one digit (multiply by 10). Remove the last digit from the original number by dividing by 10 and repeating until the original number is zero.Algorithm
Code
<?php $num = 1234; $reversed = 0; while ($num > 0) { $digit = $num % 10; $reversed = $reversed * 10 + $digit; $num = (int)($num / 10); } echo $reversed; ?>
Dry Run
Let's trace reversing 1234 through the code
Initial values
$num = 1234, $reversed = 0
First loop iteration
digit = 1234 % 10 = 4; reversed = 0 * 10 + 4 = 4; num = (int)(1234 / 10) = 123
Second loop iteration
digit = 123 % 10 = 3; reversed = 4 * 10 + 3 = 43; num = (int)(123 / 10) = 12
Third loop iteration
digit = 12 % 10 = 2; reversed = 43 * 10 + 2 = 432; num = (int)(12 / 10) = 1
Fourth loop iteration
digit = 1 % 10 = 1; reversed = 432 * 10 + 1 = 4321; num = (int)(1 / 10) = 0
Loop ends
num is 0, exit loop, reversed = 4321
| num | digit | reversed |
|---|---|---|
| 1234 | 4 | 4 |
| 123 | 3 | 43 |
| 12 | 2 | 432 |
| 1 | 1 | 4321 |
Why This Works
Step 1: Extract last digit
Using % 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.
Step 3: Remove last digit
Divide the original number by 10 and convert to integer to remove the last digit for the next iteration.
Alternative Approaches
<?php $num = 1234; $reversed = strrev((string)$num); echo (int)$reversed; ?>
<?php function reverseNumber($num, $reversed = 0) { if ($num == 0) return $reversed; return reverseNumber((int)($num / 10), $reversed * 10 + $num % 10); } echo reverseNumber(1234); ?>
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.
Space Complexity
Only a few variables are used, so space is constant regardless of input size.
Which Approach is Fastest?
The arithmetic loop method is fastest and uses least memory; string reversal is simpler but slightly slower due to string operations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic loop | O(d) | O(1) | Performance and memory efficiency |
| String reversal | O(d) | O(d) | Simplicity and quick coding |
| Recursive reversal | O(d) | O(d) | Elegant code but uses more memory |
(int)($num / 10) to remove the last digit safely in PHP.