Check if actual binary representation of a number is palindrome
Last Updated :
01 Aug, 2022
Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0’s are being considered.
Examples :
Input : 9
Output : Yes
(9)10 = (1001)2
Input : 10
Output : No
(10)10 = (1010)2
Approach: Following are the steps:
- Get the number obtained by reversing the bits in the binary representation of n. Refer this post. Let it be rev.
- If n == rev, then print “Yes” else “No”.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
unsigned int reverseBits(unsigned int n)
{
unsigned int rev = 0;
while (n > 0) {
rev <<= 1;
if (n & 1 == 1)
rev ^= 1;
n >>= 1;
}
return rev;
}
bool isPalindrome(unsigned int n)
{
unsigned int rev = reverseBits(n);
return (n == rev);
}
int main()
{
unsigned int n = 9;
if (isPalindrome(n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
public class GfG
{
public static long reverseBits( long n)
{
long rev = 0 ;
while (n > 0 )
{
rev <<= 1 ;
if ((n & 1 ) == 1 )
rev ^= 1 ;
n >>= 1 ;
}
return rev;
}
public static boolean isPalindrome( long n)
{
long rev = reverseBits(n);
return (n == rev);
}
public static void main(String argc[])
{
long n = 9 ;
if (isPalindrome(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def reverseBits(n) :
rev = 0
while (n > 0 ) :
rev = rev << 1
if (n & 1 = = 1 ) :
rev = rev ^ 1
n = n >> 1
return rev
def isPalindrome(n) :
rev = reverseBits(n)
return (n = = rev)
n = 9
if (isPalindrome(n)) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
public class GfG
{
public static long reverseBits( long n)
{
long rev = 0;
while (n > 0)
{
rev <<= 1;
if ((n & 1) == 1)
rev ^= 1;
n >>= 1;
}
return rev;
}
public static bool isPalindrome( long n)
{
long rev = reverseBits(n);
return (n == rev);
}
public static void Main()
{
long n = 9;
if (isPalindrome(n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function reverseBits( $n )
{
$rev = 0;
while ( $n > 0)
{
$rev <<= 1;
if ( $n & 1 == 1)
$rev ^= 1;
$n >>= 1;
}
return $rev ;
}
function isPalindrome( $n )
{
$rev = reverseBits( $n );
return ( $n == $rev );
}
$n = 9;
if (isPalindrome( $n ))
echo "Yes" ;
else
echo "No" ;
return 0;
?>
|
Javascript
<script>
function reverseBits(n)
{
let rev = 0;
while (n > 0)
{
rev <<= 1;
if ((n & 1) == 1)
rev ^= 1;
n >>= 1;
}
return rev;
}
function isPalindrome(n)
{
let rev = reverseBits(n);
return (n == rev);
}
let n = 9;
if (isPalindrome(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(num), where num is the number of bits in the binary representation of n.
Auxiliary Space: O(1).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...