Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Golang Program to check if the binary representation of a number is palindrome or not
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
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
Advertisements
