Friday, December 27, 2024
Google search engine
HomeLanguagesJavaCheck if binary representation of a number is palindrome

Check if binary representation of a number is palindrome

Given an integer ‘x’, write a C function that returns true if binary representation of x is palindrome else return false.
For example a numbers with binary representation as 10..01 is palindrome and number with binary representation as 10..00 is not palindrome.
The idea is similar to checking a string is palindrome or not. We start from leftmost and rightmost bits and compare bits one by one. If we find a mismatch, then return false. 

Method#1:  We follow the following logic to check binary of number is Palindrome or not:

  • Find number of bits in x using sizeof() operator. 
  • Initialize left and right positions as 1 and n respectively. 
  • Do following while left ‘l’ is smaller than right ‘r’. 
    • If bit at position ‘l’ is not same as bit at position ‘r’, then return false. 
    • Increment ‘l’ and decrement ‘r’, i.e., do l++ and r–-. 
  •  If we reach here, it means we didn’t find a mismatching bit.
  • To find the bit at a given position, we can use an idea similar to this post. The expression “x & (1 << (k-1))” gives us non-zero value if bit at k’th position from right is set and gives a zero value if if k’th bit is not set.

Following is the implementation of the above algorithm 

C++




// C++ Program to Check if binary representation
// of a number is palindrome
#include<iostream>
using namespace std;
 
// This function returns true if k'th bit in x
// is set (or 1). For example if x (0010) is 2
// and k is 2, then it returns true
bool isKthBitSet(unsigned int x, unsigned int k)
{
    return (x & (1 << (k - 1))) ? true : false;
}
 
// This function returns true if binary
// representation of x is palindrome.
// For example (1000...001) is palindrome
bool isPalindrome(unsigned int x)
{
    int l = 1; // Initialize left position
    int r = sizeof(unsigned int) * 8; // initialize right position
 
    // One by one compare bits
    while (l < r)
    {
        if (isKthBitSet(x, l) != isKthBitSet(x, r))
            return false;
        l++; r--;
    }
    return true;
}
 
// Driver Code
int main()
{
    unsigned int x = 1 << 15 + 1 << 16;
    cout << isPalindrome(x) << endl;
    x = 1 << 31 + 1;
    cout << isPalindrome(x) << endl;
    return 0;
}


Java




// Java Program to Check if binary representation
// of a number is palindrome
class GFG
{
 
    // This function returns true if k'th bit in x
    // is set (or 1). For example if x (0010) is 2
    // and k is 2, then it returns true
    static int isKthBitSet(long x, long k)
    {
        int rslt = ((x & (1 << (k - 1))) != 0) ? 1 : 0;
        return rslt;
    }
     
    // This function returns true if binary
    // representation of x is palindrome.
    // For example (1000...001) is palindrome
    static int isPalindrome( long x)
    {
        long l = 1; // Initialize left position
        long r = (Integer.SIZE/8 )* 8; // initialize right position
     
        // One by one compare bits
        while (l < r)
        {
            if (isKthBitSet(x, l) != isKthBitSet(x, r))
            {
                return 0;
            }
            l++; r--;
        }
        return 1;
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        long x = 1 << 15 + 1 << 16 ;
        System.out.println(isPalindrome(x));
         
        x = (1 << 31) + 1 ;
        System.out.println(isPalindrome(x));
    }
}
 
// This code is contributed by AnkitRai01


Python3




# python 3 Program to Check if binary representation
# of a number is palindrome
import sys
# This function returns true if k'th bit in x
# is set (or 1). For example if x (0010) is 2
# and k is 2, then it returns true
def isKthBitSet(x, k):
    if ((x & (1 << (k - 1))) !=0):
        return True
    else:
        return False
 
# This function returns true if binary
# representation of x is palindrome.
# For example (1000...001) is palindrome
def isPalindrome(x):
    l = 1 # Initialize left position
    r = 2 * 8 # initialize right position
 
    # One by one compare bits
    while (l < r):
        if (isKthBitSet(x, l) != isKthBitSet(x, r)):
            return False
        l += 1
        r -= 1
     
    return True
 
# Driver Code
if __name__ =='__main__':
    x = 1 << 15 + 1 << 16
    print(int(isPalindrome(x)))
    x = 1 << 31 + 1
    print(int(isPalindrome(x)))
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# Program to Check if binary representation
// of a number is palindrome
using System;
 
class GFG
{
 
    // This function returns true if k'th bit in x
    // is set (or 1). For example if x (0010) is 2
    // and k is 2, then it returns true
    static int isKthBitSet(long x, long k)
    {
        int rslt = ((x & (1 << (int)(k - 1))) != 0) ? 1 : 0;
        return rslt;
    }
     
    // This function returns true if binary
    // representation of x is palindrome.
    // For example (1000...001) is palindrome
    static int isPalindrome( long x)
    {
        long l = 1; // Initialize left position
        long r = 4 * 8; // initialize right position
     
        // One by one compare bits
        while (l < r)
        {
            if (isKthBitSet(x, l) != isKthBitSet(x, r))
            {
                return 0;
            }
            l++; r--;
        }
        return 1;
    }
     
    // Driver Code
    public static void Main ()
    {
        long x = 1 << 15 + 1 << 16 ;
        Console.WriteLine(isPalindrome(x));
         
        x = (1 << 31) + 1 ;
        Console.WriteLine(isPalindrome(x));
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
 
// Javascript program to Check if binary
// representation of a number is palindrome
 
// This function returns true if k'th bit in x
// is set (or 1). For example if x (0010) is 2
// and k is 2, then it returns true
function isKthBitSet(x, k)
{
    let rslt = ((x & (1 << (k - 1))) != 0) ? 1 : 0;
    return rslt;
}
   
// This function returns true if binary
// representation of x is palindrome.
// For example (1000...001) is palindrome
function isPalindrome(x)
{
     
    // Initialize left position
    let l = 1;
     
    // initialize right position
    let r = 4 * 8;
   
    // One by one compare bits
    while (l < r)
    {
        if (isKthBitSet(x, l) !=
            isKthBitSet(x, r))
        {
            return 0;
        }
        l++; r--;
    }
    return 1;
}
 
// Driver code
let x = 1 << 15 + 1 << 16;
document.write(isPalindrome(x) + "</br>");
 
x = (1 << 31) + 1;
document.write(isPalindrome(x));
 
// This code is contributed by divyesh072019
 
</script>


PHP




<?php
// PHP Program to Check if binary representation
// of a number is palindrome
 
// This function returns true if k'th bit in x
// is set (or 1). For example if x (0010) is 2
// and k is 2, then it returns true
function isKthBitSet($x, $k)
{
    return ($x & (1 << ($k - 1))) ? true : false;
}
 
// This function returns true if binary
// representation of x is palindrome.
// For example (1000...001) is palindrome
function isPalindrome($x)
{
    $l = 1; // Initialize left position
    $r = sizeof(4) * 8; // initialize right position
 
    // One by one compare bits
    while ($l < $r)
    {
        if (isKthBitSet($x, $l) != isKthBitSet($x, $r))
            return false;
        $l++;
        $r--;
    }
    return true;
}
 
// Driver Code
$x = 1 << 15 + 1 << 16;
echo isPalindrome($x), "\n";
$x = 1 << 31 + 1;
echo isPalindrome($x), "\n";
 
// This code is contributed by ajit.
?>


Output

1
1



Time Complexity: O(x)
Auxiliary Space: O(1)

Method#2: Using reverse() function: 

  • When user inputs an integer, it is passed to method which will evaluate the result. 
  • Actual logic inside the method focuses on following: 
    • It first convert the integer to binary form of integer in string format. 
    • It reverse the string using reverse method. 
    • It is palindrome if both the string is equal else not. 

Below is the implementation of the above approach: 

C++




// C++ program to check if binary representation
// of a number is palindrome
#include <bits/stdc++.h>
using namespace std;
 
// This function return the binary form of integer in string format
string bin(unsigned n)
{   string ans;
    while(n > 0){
        ans = (to_string(n&1)) + ans;
        n >>= 1;
    }
     
    return ans;
}
 
// This function returns true if binary
// representation of x is palindrome
bool checkPalindrome( unsigned int n){
    string s1 = bin(n);
    string s2 = s1;
     
    // reversing the string 1
    reverse(s2.begin(), s2.end());
     
    return s1 == s2;
}
 
// Driver code
int main() {
    unsigned int x = 1 << 15 + 1 << 16;
    cout << checkPalindrome(x) << endl;
    x = 10;
    cout << checkPalindrome(x) << endl;
    return 0;
}


Java




// Java program to check if binary representation
// of a number is palindrome
class GFG
{
   
  // This function return the binary form of integer in string format
  static String bin(int n)
  {  
    String ans = "";
    while(n > 0){
      ans = (Integer.toString(n&1)) + ans;
      n >>= 1;
    }
 
    return ans;
  }
 
  // This function returns true if binary
  // representation of x is palindrome
  static int checkPalindrome(int n){
    String s1 = bin(n);
 
    // reversing the string 1
    StringBuilder s2 = new StringBuilder(s1);
    s2 = s2.reverse();
 
 
    return s1.equals(s2.toString()) ? 1 : 0;
  }
 
  public static void main(String[] args) {
    int x = 9;
    System.out.println(checkPalindrome(x));
    x = 10;
    System.out.println(checkPalindrome(x)); 
  }
}
 
// This code is contributed by phasing17.


Python




def bin(n):
    ans="";
    while n > 0:
        ans = (str(n&1)) + ans;
        n >>= 1;
    return ans;
 
def checkPalindrome(x):
    s1 = bin(x)
    s2 = s1[::-1]
    return 1 if s1 == s2 else 0
 
# Some test cases....
x = 9
print(checkPalindrome(x)) #  output 1
 
x = 10
print(checkPalindrome(x)) # output 0


C#




// C# program to check if binary representation
// of a number is palindrome
using System;
 
public class GFG
{
 
  // This function returns the binary form of integer in
  // string format
  static string bin(int n)
  {
    string ans = "";
    while (n > 0) {
      ans = (Convert.ToString(n & 1)) + ans;
      n >>= 1;
    }
 
    return ans;
  }
 
  // This function returns true if binary
  // representation of x is palindrome
  static int checkPalindrome(int n)
  {
    string s1 = bin(n);
 
    // reversing the string 1
    char[] charArray = s1.ToCharArray();
    Array.Reverse(charArray);
    string s2 = new string(charArray);
 
    return s1.Equals(s2) ? 1 : 0;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    int x = 9;
    Console.WriteLine(checkPalindrome(x));
    x = 10;
    Console.WriteLine(checkPalindrome(x));
  }
}
 
// This code is contributed by phasing17.


Javascript




// JavaScript program to check if binary representation
// of a number is palindrome
 
// This function return the binary form of integer in string format
function bin(n)
{   let ans="";
    while(n > 0){
        ans = ((n&1).toString()) + ans;
        n >>= 1;
    }
     
    return ans;
}
 
// This function returns true if binary
// representation of x is palindrome
function checkPalindrome(x){
    let s1 = bin(x);
    // reversing the string s1
    let s2 = s1.split("").reverse().join("");
    return s1 === s2 ? 1 :0;
}
 
// Some test case
let x = 1 << 15 + 1 << 16 ;
console.log(checkPalindrome(x));
 
x = 10;
console.log(checkPalindrome(x));


Output

1
0



Time Complexity: O(log(x))
Auxiliary Space: O(X)

Method 3: Using builtin method bitset<>

  • Convert the given number into its binary form.
  • Check if it’s palindrome or not.

Below is the implementation of the above approach:

C++




// C++ program to check if binary representation
// of a number is palindrome
#include <bits/stdc++.h>
using namespace std;
 
int isPalindrome(int N)
{
    // Converting N into binary representation
    string s = bitset<32>(N).to_string();
    s = s.substr(s.find('1'));
 
    // Checking if it is palindrome or not
    int i = 0, j = s.size() - 1;
    while (i < j) {
        if (s[i] != s[j])
            return false;
        i++;
        j--;
    }
    return true;
}
 
// Driver code
int main()
{
    int x = 16;
    cout << isPalindrome(x) << endl;
    x = 17;
    cout << isPalindrome(x) << endl;
    return 0;
}
 
// This code is contributed by hkdass001


Java




// Java code for the above approach
import java.io.*;
 
class Main {
  public static boolean isPalindrome(int N)
  {
     
    // Converting N into binary representation
    String s = Integer.toBinaryString(N);
     
    // Checking if it is palindrome or not
    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) {
    int x = 16;
    System.out.println(isPalindrome(x));
    x = 17;
    System.out.println(isPalindrome(x));
  }
}
 
// This code is contributed by lokeshpotta20.


Python3




# Python program to check if binary representation
# of a number is palindrome
import math
 
def isPalindrome(N):
    # Converting N into binary representation
    s = bin(N)[2:] 
    s = s[s.index('1'):]   
    # Checking if it is palindrome or not
    i = 0;
    j = len(s) - 1;
    while (i < j):
        if (s[i] != s[j]):
            return 0;
        i+=1;
        j-=1;
    return 1;
 
# Driver code
x = 16;
print(isPalindrome(x));
x = 17;
print(isPalindrome(x));


C#




// C# program to check if binary representation
// of a number is palindrome
 
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG
{
 
    static int isPalindrome(int N)
    {
        // Converting N into binary representation
        string s = Convert.ToString(N,2);
 
        // Checking if it is palindrome or not
        int i = 0, j = s.Length - 1;
        while (i < j) {
            if (s[i] != s[j])
                return 0;
            i++;
            j--;
        }
        return 1;
    }
     
    // Driver code
    static public void Main()
    {
        int x = 16;
        Console.WriteLine(isPalindrome(x));
        x = 17;
        Console.WriteLine(isPalindrome(x));
    }
}


Javascript




// Javascript program to check if binary representation
// of a number is palindrome
function isPalindrome(N)
{
    // Converting N into binary representation
    const s = N.toString(2);
     
    // Checking if it is palindrome or not
    let i = 0, j = s.length - 1;
    while (i < j) {
        if (s[i] != s[j])
            return 0;
        i++;
        j--;
    }
    return 1;
}
 
// Driver code
let x = 16;
console.log(isPalindrome(x));
x = 17;
console.log(isPalindrome(x));
 
// This code is contributed by agrawalpoojaa976.


Output

0
1



Time Complexity: O(k), where k is the number of bits in the given number X
Auxiliary Space: O(k)

This article is contributed by Saurabh Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Approach#4: using | operator

This approach uses bitwise operations to reverse the binary representation of a number and then checks if it is equal to the original binary representation, indicating whether or not it is a palindrome.

Algorithm

1. Create a copy of the input number and initialize a variable to hold the reversed binary representation.
2. Loop through the bits of the input number and append each bit to the reversed binary representation.
3. Convert the reversed binary representation to an integer and compare it with the original number.
4. If the two numbers are equal, return True, else return False.

C++




#include <iostream>
using namespace std;
 
bool is_binary_palindrome(int num) {
    int rev_binary = 0;
    int copy_num = num;
    while (copy_num) {
        rev_binary = (rev_binary << 1) | (copy_num & 1);
        copy_num >>= 1;
    }
    return rev_binary == num;
}
 
int main() {
    int num = 9;
    cout << is_binary_palindrome(num) << endl;
    num = 10;
    cout << is_binary_palindrome(num) << endl;
    return 0;
}


Java




public class Main {
    public static boolean isBinaryPalindrome(int num) {
        int revBinary = 0;
        int copyNum = num;
        while (copyNum != 0) {
            revBinary = (revBinary << 1) | (copyNum & 1);
            copyNum >>= 1;
        }
        return revBinary == num;
    }
 
    public static void main(String[] args) {
        int num = 9;
        System.out.println(isBinaryPalindrome(num));
        num = 10;
        System.out.println(isBinaryPalindrome(num));
    }
}


Python3




def is_binary_palindrome(num):
    rev_binary = 0
    copy_num = num
    while copy_num:
        rev_binary = (rev_binary << 1) | (copy_num & 1)
        copy_num >>= 1
    return rev_binary == num
 
num=9
print(is_binary_palindrome(num))
num=10
print(is_binary_palindrome(num))


C#




using System;
 
class GFG {
    public static bool IsBinaryPalindrome(int num) {
        int revBinary = 0;
        int copyNum = num;
        while (copyNum != 0) {
            revBinary = (revBinary << 1) | (copyNum & 1);
            copyNum >>= 1;
        }
        return revBinary == num;
    }
 
    public static void Main(string[] args) {
        int num = 9;
        Console.WriteLine(IsBinaryPalindrome(num));
        num = 10;
        Console.WriteLine(IsBinaryPalindrome(num));
    }
}


Javascript




class GFG {
    // Function to check if a given decimal number is a palindrome in binary representation
    static IsBinaryPalindrome(num) {
        let revBinary = 0;
        let copyNum = num;
         
        // Convert the decimal number to its binary representation and reverse it
        while (copyNum !== 0) {
           // Left shift revBinary by 1 and add the least significant bit of copyNum
            revBinary = (revBinary << 1) | (copyNum & 1);
            copyNum >>= 1; // Right shift copyNum by 1 to process the next bit
        }
         
        // Check if the reversed binary representation is equal to the original decimal number
        return revBinary === num;
    }
 
    static main() {
        let num = 9;
        console.log(GFG.IsBinaryPalindrome(num)); // Output: true
        num = 10;
        console.log(GFG.IsBinaryPalindrome(num)); // Output: false
    }
}
 
// Call the main function to execute the code
GFG.main();


Output

True
False



Time Complexity: O(log n), where n is the value of the input number.
Auxiliary Space: O(1), for storing the loop variable and reversed binary representation.

RELATED ARTICLES

Most Popular

Recent Comments