Write a Go Program to Reverse a Number using for loop. The for loop condition make sure the number is greater than zero. Within the loop (for revnum > 0),
- remainder = revnum % 10 – Assigning the last digit in a number to the remainder.
- reverse = reverse * 10 + remainder – Multiplies the reverse value with ten and adds the remainder value to it.
- revnum = revnum / 10 – Removes the last digit from the revnum
package main import "fmt" func main() { var revnum, remainder int fmt.Print("Enter the Number to Reverse = ") fmt.Scanln(&revnum) reverse := 0 for revnum > 0 { remainder = revnum % 10 reverse = reverse*10 + remainder revnum = revnum / 10 } fmt.Println("The Reverse of the Given Number = ", reverse) }
Go Program to Reverse a Number using Functions
package main import "fmt" func numberReverse(revnum int) int { var remainder int reverse := 0 for ; revnum > 0; revnum = revnum / 10 { remainder = revnum % 10 reverse = reverse*10 + remainder } return reverse } func main() { var revnum int fmt.Print("Enter the Number to Reverse = ") fmt.Scanln(&revnum) reverse := numberReverse(revnum) fmt.Println("The Reverse of the Given Number = ", reverse) }
SureshMac:GoExamples suresh$ go run reversenum2.go
Enter the Number to Reverse = 3487
The Reverse of the Given Number = 7843
SureshMac:GoExamples suresh$ go run reversenum2.go
Enter the Number to Reverse = 90764
The Reverse of the Given Number = 46709
In this Golang example, we declared a recursive function to reverse the given number. Here, number_reverse (revnum / 10) calls the number_reverse() function recursively.
package main import "fmt" var reverse int = 0 func numberReverse(revnum int) int { var remainder int if revnum <= 0 { return 0 } remainder = revnum % 10 reverse = reverse*10 + remainder numberReverse(revnum / 10) return reverse } func main() { var revnum int fmt.Print("Enter the Number to Reverse = ") fmt.Scanln(&revnum) reverse := numberReverse(revnum) fmt.Println("The Reverse of the Given Number = ", reverse) }
SureshMac:GoExamples suresh$ go run reversenum3.go
Enter the Number to Reverse = 3098
The Reverse of the Given Number = 8903
SureshMac:GoExamples suresh$ go run reversenum3.go
Enter the Number to Reverse = 390754
The Reverse of the Given Number = 457093