Go Program to Reverse a Number with Output and Explanation
num % 10, adding it to a reversed number multiplied by 10, and then removing the last digit from the original number using num /= 10 until the original number becomes zero.Examples
How to Think About It
%. Then build the reversed number by shifting the current reversed number left by one digit (multiply by 10) and adding the peeled digit. Repeat until the original number is fully processed.Algorithm
Code
package main import "fmt" func reverseNumber(num int) int { reversed := 0 for num > 0 { digit := num % 10 reversed = reversed*10 + digit num /= 10 } return reversed } func main() { number := 12345 fmt.Println(reverseNumber(number)) }
Dry Run
Let's trace reversing 12345 through the code
Initial values
num = 12345, reversed = 0
First iteration
digit = 12345 % 10 = 5; reversed = 0*10 + 5 = 5; num = 12345 / 10 = 1234
Second iteration
digit = 1234 % 10 = 4; reversed = 5*10 + 4 = 54; num = 1234 / 10 = 123
Third iteration
digit = 123 % 10 = 3; reversed = 54*10 + 3 = 543; num = 123 / 10 = 12
Fourth iteration
digit = 12 % 10 = 2; reversed = 543*10 + 2 = 5432; num = 12 / 10 = 1
Fifth iteration
digit = 1 % 10 = 1; reversed = 5432*10 + 1 = 54321; num = 1 / 10 = 0
Loop ends
num is 0, return reversed = 54321
| num | digit | reversed |
|---|---|---|
| 12345 | 5 | 5 |
| 1234 | 4 | 54 |
| 123 | 3 | 543 |
| 12 | 2 | 5432 |
| 1 | 1 | 54321 |
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 new digit to append it.
Step 3: Remove last digit
Divide the original number by 10 using num /= 10 to remove the last digit and continue.
Alternative Approaches
package main import ( "fmt" "strconv" ) func reverseNumberString(num int) int { s := strconv.Itoa(num) reversedStr := "" for i := len(s) - 1; i >= 0; i-- { reversedStr += string(s[i]) } reversedNum, _ := strconv.Atoi(reversedStr) return reversedNum } func main() { fmt.Println(reverseNumberString(12345)) }
package main import "fmt" func reverseNumberRec(num, reversed int) int { if num == 0 { return reversed } return reverseNumberRec(num/10, reversed*10+num%10) } func main() { fmt.Println(reverseNumberRec(12345, 0)) }
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 constant, O(1).
Which Approach is Fastest?
The arithmetic approach is fastest and uses least memory compared to string conversion or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Arithmetic loop | O(d) | O(1) | Efficient and simple for all numbers |
| String conversion | O(d) | O(d) | Easy to understand but less efficient |
| Recursive | O(d) | O(d) | Elegant but uses more stack memory |