Reverse a Number in Go
In this tutorial, we will learn how to reverse a number in Go. We will cover the basic concept of number manipulation and implement a function to perform the reversal.
What is Number Reversal
Number reversal involves rearranging the digits of a number in the opposite order. For example, reversing 12345 results in 54321.
Syntax
The syntax to reverse a number in Go is:
func reverseNumber(n int) int {
reversed := 0
for n != 0 {
remainder := n % 10
reversed = reversed*10 + remainder
n = n / 10
}
return reversed
}
Example 1: Reversing a number
We can create a function to reverse a given number by extracting its digits and constructing the reversed number.
For example,
- Define a function named
reverseNumber
that takes one parametern
of typeint
. - Initialize a variable
reversed
to 0 to store the reversed number. - Use a
for
loop to iterate whilen
is not 0. - In each iteration, extract the last digit of
n
using the modulo operator and add it toreversed
after multiplyingreversed
by 10. - Remove the last digit from
n
by dividing it by 10. - Return the reversed number.
- In the main function, call the
reverseNumber
function with a sample number and print the result.
Go Program
package main
import (
"fmt"
)
func reverseNumber(n int) int {
reversed := 0
for n != 0 {
remainder := n % 10
reversed = reversed*10 + remainder
n = n / 10
}
return reversed
}
func main() {
// Sample number
number := 12345
// Reverse the number
result := reverseNumber(number)
// Print the result
fmt.Printf("Reversed number is: %d\n", result)
}
Output
Reversed number is: 54321