Write a Golang program to reverse a number

Go ProgrammingServer Side ProgrammingProgramming

Examples

  • Input num = 1432 => output = 2341
  • Input num = 9878 => output = 8789
  • Input num = 6785 => output = 5876

Approach to solve this problem

  • Step 1: Define a function that accepts a number (num); type is int.
  • Step 2: Define res = 0 variable and start a loop until num becomes 0.
  • Step 3: Find remainder = num % 10 and make a number.
  • Step 4: Divide num by 10.
  • Step 5: Return res.

Program

Live Demo

package main
import "fmt"
func reverseNumber(num int) int {

   res := 0
   for num>0 {
      remainder := num % 10
      res = (res * 10) + remainder
      num /= 10
   }
   return res
}

func main(){
   fmt.Println(reverseNumber(168))
   fmt.Println(reverseNumber(576))
   fmt.Println(reverseNumber(12345))
}

Output

861
675
54321
raja
Published on 04-Feb-2021 11:03:01
Advertisements