Go - Palindrome Program Example
If a number/string, which when read in both forward and backward way is the same, then such a number is called a palindrome number.
Example 1. Go Program to check whether the given number is Palindrome or not
//Check Whether a Number is Palindrome or Notpackage main
import "fmt"
// Main functionfunc main() {
number1 := 121 number2 := 125 number3 := 125521 IsPalindrome(number1) IsPalindrome(number2) IsPalindrome(number3)
}func IsPalindrome(number int) { var lastDigit int sum := 0 a := number
// Code to reverse a number for a != 0 { lastDigit = a % 10 //getting remainder sum = (sum * 10) + lastDigit a = a / 10 } /*If given number equal to sum than number is palindrome otherwise not palindrome*/ if sum == number { fmt.Println(number, " is palindrome ") } else { fmt.Println(number, " is not palindrome") }}
Output:
Example 2. Go Program to check whether the given String is Palindrome or not
//Check Whether a String is Palindrome or Notpackage main
import "fmt"
// Main functionfunc main() {
str1 := "hello" str2 := "iTopiNonAvevAnoNipoTi" str3 := "121" IsPalindrome(str1) IsPalindrome(str2) IsPalindrome(str3)
}func IsPalindrome(str string) { var reverse string
// Code to reverse a string for i := len(str) - 1; i >= 0; i-- { reverse = reverse + string(str[i]) }
if str == reverse { fmt.Println(str, " is palindrome ") } else { fmt.Println(str, " is not palindrome") }}
Output:
Example 3. Go Program to check whether the input number is Palindrome or not
//Check Whether a Number is Palindrome or Notpackage main
import "fmt"
// Main functionfunc main() {
var number int fmt.Println("Enter the number : ")
_, err := fmt.Scanf("%d", &number)
if err != nil { fmt.Println(err) } IsPalindrome(number)
}func IsPalindrome(number int) { var lastDigit int sum := 0 a := number
// Code to reverse a number for a != 0 { lastDigit = a % 10 //getting remainder sum = (sum * 10) + lastDigit a = a / 10 } /*If given number equal to sum than number is palindrome otherwise not palindrome*/ if sum == number { fmt.Println(number, " is palindrome ") } else { fmt.Println(number, " is not palindrome") }}
Output:
Example 4. Go Program to check whether the input String is Palindrome or not
//Check Whether a String is Palindrome or Notpackage main
import "fmt"
// Main functionfunc main() {
var str string fmt.Println("Enter the string : ")
fmt.Scanln(&str)
IsPalindrome(str)
}func IsPalindrome(str string) { var reverse string
// Code to reverse a string for i := len(str) - 1; i >= 0; i-- { reverse = reverse + string(str[i]) }
if str == reverse { fmt.Println(str, " is palindrome ") } else { fmt.Println(str, " is not palindrome") }}