Golang Program to check if the binary representation of a number is palindrome or not

Go ProgrammingServer Side ProgrammingProgramming

Examples

For example, 101, 11, 11011, 1001001 are Palindrome. 100, 10010 are not Palindrome.

Approach to solve this problem

Step 1 − Convert number into binary representation.

Step 2 − Traverse the converted binary representation from both side and check whether representation is palindrome or not.

Example

 Live Demo

package main
import (
   "fmt"
   "strconv"
)
func IsPalindrome(n int) bool{
   rev := 0
   k := n
   for k != 0 {
      rev = (rev << 1) | (k & 1)
      k = k >> 1
   }
   return n == rev
}
func main(){
   n := 3
   fmt.Printf("Binary representation of %d is: %s.\n", n,
   strconv.FormatInt(int64(n), 2))
   if IsPalindrome(n) == true{
      fmt.Println("Palindrome")
   } else {
      fmt.Println("Not a Palindrome")
   }
}

Output

Binary representation of 3 is: 11.
Palindrome
raja
Published on 17-Mar-2021 11:21:51
Advertisements