Professional Documents
Culture Documents
Winsem2023-24 Msts601l TH Ch2023240503480 Reference Material I 05-02-2024 Binary Palindrome
Winsem2023-24 Msts601l TH Ch2023240503480 Reference Material I 05-02-2024 Binary Palindrome
Winsem2023-24 Msts601l TH Ch2023240503480 Reference Material I 05-02-2024 Binary Palindrome
BINARY PALINDROME
Introduction
You are given an integer ‘X’, you need to convert the integer to binary
format and check if the binary format is palindrome or not
For Example, 5 i.e. 101, 27 i.e. 11011 are numbers whose binary
representations are palindromes. Whereas 10 i.e. 1011 and 20 i.e. 10100 are
not palindromes
BINARY PALINDROME
We start from leftmost and rightmost bits and compare bits one by one. If
we find a mismatch, then return false.
A special caution that you should not consider the leading zeros,
while considering the binary representation.
Programs
Sample IO
Input : 1
Output : 1
1st Number whose binary representation
is palindrome is 1 (1)
Input : 9
Output : 27
9th Number whose binary representation
is palindrome is 27 (11011)
BINARY PALINDROME
class GFG
{ public static void main(String[] args) {
static String bin(int n) int x = 9;
{ System.out.println(checkPalindrome(x));
String ans = ""; x = 10;
while(n > 0){ System.out.println(checkPalindrome(x));
ans = (Integer.toString(n&1)) + ans; }
n >>= 1; }
}
return ans;
}
static int checkPalindrome(int n){
String s1 = bin(n);
StringBuilder s2 = new
StringBuilder(s1);
s2 = s2.reverse();
return s1.equals(s2.toString()) ? 1 : 0;
}
BINARY PALINDROME
https://learn.codemithra.com