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,

  1. Define a function named reverseNumber that takes one parameter n of type int.
  2. Initialize a variable reversed to 0 to store the reversed number.
  3. Use a for loop to iterate while n is not 0.
  4. In each iteration, extract the last digit of n using the modulo operator and add it to reversed after multiplying reversed by 10.
  5. Remove the last digit from n by dividing it by 10.
  6. Return the reversed number.
  7. 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