L13 - Binary Palindrome

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

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. Wheras 10 i.e. 1011 and 20 i.e. 10100 are not palindromes

The problem is very similar to checking whether a string is palindrome or not.


Hence the binary representation must be strings.

We start from leftmost and rightmost bits and compare bits one by one. If we find
a mismatch, then return false.

We can use the regular palindrome program. Converting integer ‘val’ to binary is
as easy as Integer.toBinaryString(val)
1. Binary palindrome of N=5
- Binary: 101
- Reversed binary: 101
- Explanation: The binary sequence reads the same forwards and backwards.

2. Binary palindrome of N=51


- Binary: 110011
- Reversed binary: 110011
- Explanation: The binary sequence remains unchanged when reversed.

3. Binary palindrome of N=231


- Binary: 11100111
- Reversed binary: 11100111
- Explanation: The binary sequence is the same when reversed.
P-1 import java.util.Scanner;
class Main {
public static boolean Palindrome(int N)
{
String s = Integer.toBinaryString(N);
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
public static void main(String[] args)
{
Scanner s1=new Scanner(System.in);
System.out.println("enter the number-");
int x=s1.nextInt();
System.out.println(Palindrome(x));
}
}
import java.io.*;
P-2 class Binaryy {
public static void main(String[] args)
{
int x=9;
String s = Integer.toBinaryString(x);
String s1="";
for (int i = s.length() - 1; i >= 0; i--) {
s1 = s1 + s.charAt(i);
}
if (s.equals(s1)) {
System.out.println("True");
}
else
System.out.println("False");
}
}
Find the nth number whose binary representation is
a palindrome :
A special caution that you should not consider the leading zeros, while
considering the binary representation.

Approach: Traverse through all the integers from 1 to 2^31 – 1 and


increment palindrome count, if the number is a palindrome. When the
palindrome count reaches the required n, break the loop and return the
current integer.
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)
THANK YOU

You might also like