Welcome To Golang By Example

Reverse a number or an integer in Go (Golang)

Table of Contents

Overview

The objective is to reverse a number that is an integer. Integer can be negative as well. Some examples

Input: 123
Output: 321

Input: 140
Output: 41

Input: -123
Output: -321

Input: 0
Output: 0

Here is the strategy

for x > 0 {
	lastDigit := x % 10
	reversedDigit = reversedDigit*10 + lastDigit

	x = x / 10
}

Here is the complete program for the same.

Program

package main

import (
	"fmt"
	"math"
)

func main() {
	reversedInteger := reverse(123)
	fmt.Println(reversedInteger)

	reversedInteger = reverse(140)
	fmt.Println(reversedInteger)

	reversedInteger = reverse(-123)
	fmt.Println(reversedInteger)

	reversedInteger = reverse(0)
	fmt.Println(reversedInteger)
}

func reverse(x int) int {
	sign := "positive"
	if x >= 0 {
		sign = "positive"
	} else {
		sign = "negative"
	}

	x = int(math.Abs(float64(x)))

	var reversedDigit int

	for x > 0 {
		lastDigit := x % 10
		reversedDigit = reversedDigit*10 + lastDigit

		x = x / 10
	}

	if sign == "negative" {
		reversedDigit = reversedDigit * -1
	}
	return reversedDigit
}

Output

321
41
-321
0