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.
Number reversal involves rearranging the digits of a number in the opposite order. For example, reversing 12345 results in 54321.
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
}
We can create a function to reverse a given number by extracting its digits and constructing the reversed number.
For example,
reverseNumber
that takes one parameter n
of type int
.reversed
to 0 to store the reversed number.for
loop to iterate while n
is not 0.n
using the modulo operator and add it to reversed
after multiplying reversed
by 10.n
by dividing it by 10.reverseNumber
function with a sample number and print the result.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)
}
Reversed number is: 54321