Open In App

Check if binary representation of a number is palindrome

Last Updated : 23 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer x, determine whether its binary representation is a palindrome. Return true if it is a palindrome; otherwise, return false.

Input: x = 9
Output: true
Explanation: The binary representation of 9 is 1001, which is a palindrome.

Input: x = 10
Output: false
Explanation: The binary representation of 10 is 1010, which is not a palindrome.

Compare Bits from Both Ends – O(n) Time and O(1) Space

The idea is to compare the bits of x symmetrically from both ends, just like checking if a string is a palindrome. If all corresponding bits match, the binary representation is a palindrome.

Steps to implement the above idea:

  • Find the number of bits in x.
  • Set l = 1 (leftmost bit) and r = n (rightmost bit).
  • While l < r, compare bits at positions l and r.
  • If they are different, return false; otherwise, continue.
  • If the loop completes without mismatches, return true.

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;

// Function to check if binary representation is a palindrome
bool isBinaryPalindrome(int x) {
    int n = log2(x) + 1; // Find number of bits
    int l = 0, r = n - 1;

    while (l < r) {
        // Compare bits at positions l and r
        if (((x >> l) & 1) != ((x >> r) & 1)) {
            return false;
        }
        l++;
        r--;
    }
    return true;
}

int main() {
    cout << (isBinaryPalindrome(9) ? "true" : "false") << endl;  
    cout << (isBinaryPalindrome(10) ? "true" : "false") << endl; 
    return 0;
}
Java
// Java Program to Check if binary representation 
// of a number is palindrome 
class GfG {
    // Function to check if binary representation is a palindrome
    static boolean isBinaryPalindrome(int x) {
        int n = (int)(Math.log(x) / Math.log(2)) + 1; // Find number of bits
        int l = 0, r = n - 1;

        while (l < r) {
            // Compare bits at positions l and r
            if (((x >> l) & 1) != ((x >> r) & 1)) {
                return false;
            }
            l++;
            r--;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isBinaryPalindrome(9) ? "true" : "false");  
        System.out.println(isBinaryPalindrome(10) ? "true" : "false"); 
    }
}
Python
import math

# Function to check if binary representation is a palindrome
def is_binary_palindrome(x):
    n = int(math.log2(x)) + 1  # Find number of bits
    l, r = 0, n - 1

    while l < r:
        # Compare bits at positions l and r
        if ((x >> l) & 1) != ((x >> r) & 1):
            return False
        l += 1
        r -= 1
    return True

if __name__ == "__main__":
    print("true" if is_binary_palindrome(9) else "false")  
    print("true" if is_binary_palindrome(10) else "false") 
C#
// C# Program to Check if binary representation 
// of a number is palindrome 
using System;

class GfG {
    // Function to check if binary representation is a palindrome
    public static bool IsBinaryPalindrome(int x) {
        int n = (int)(Math.Log(x) / Math.Log(2)) + 1; // Find number of bits
        int l = 0, r = n - 1;

        while (l < r) {
            // Compare bits at positions l and r
            if (((x >> l) & 1) != ((x >> r) & 1)) {
                return false;
            }
            l++;
            r--;
        }
        return true;
    }

    public static void Main() {
        Console.WriteLine(IsBinaryPalindrome(9) ? "true" : "false");  
        Console.WriteLine(IsBinaryPalindrome(10) ? "true" : "false"); 
    }
}
JavaScript
// Function to check if binary representation is a palindrome
function isBinaryPalindrome(x) {
    let n = Math.floor(Math.log2(x)) + 1; // Find number of bits
    let l = 0, r = n - 1;

    while (l < r) {
        // Compare bits at positions l and r
        if (((x >> l) & 1) !== ((x >> r) & 1)) {
            return false;
        }
        l++;
        r--;
    }
    return true;
}

console.log(isBinaryPalindrome(9) ? "true" : "false");  
console.log(isBinaryPalindrome(10) ? "true" : "false"); 

Output
true
false

Time Complexity: O(n), where n is the number of bits in the binary representation.
Space Complexity: O(1) as only a few integer variables are used.

Using reverse() Function – O(n) Time and O(n) Space

The idea is to convert the integer into its binary representation as a string and then check if the string is a palindrome using the reverse() function.

Steps to implement the above idea:

  • Convert the given integer x into its binary representation (without the 0b prefix).
  • Store the binary string in a variable.
  • Reverse the binary string using the reverse() function or equivalent.
  • Compare the original binary string with its reversed version.
  • If both strings are equal, return true; otherwise, return false.

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;

// Function to check if binary representation is a palindrome
bool isBinaryPalindrome(int x) {
    string binary = bitset<32>(x).to_string(); // Convert to binary
    binary = binary.substr(binary.find('1')); // Remove leading zeros
    
    string revBinary = binary; 
    reverse(revBinary.begin(), revBinary.end()); // Reverse the string
    
    return binary == revBinary; // Check if palindrome
}

int main() {
    cout << (isBinaryPalindrome(9) ? "true" : "false") << endl;
    cout << (isBinaryPalindrome(10) ? "true" : "false") << endl;
    return 0;
}
Java
// Java program to check if binary representation 
// of a number is palindrome
import java.util.*;

class GfG {
    // Function to check if binary representation is a palindrome
    static boolean isBinaryPalindrome(int x) {
        String binary = Integer.toBinaryString(x); // Convert to binary
        String revBinary = new StringBuilder(binary).reverse().toString(); // Reverse the string
        
        return binary.equals(revBinary); // Check if palindrome
    }

    public static void main(String[] args) {
        System.out.println(isBinaryPalindrome(9) ? "true" : "false");
        System.out.println(isBinaryPalindrome(10) ? "true" : "false");
    }
}
Python
# Python program to check if binary representation 
# of a number is palindrome

# Function to check if binary representation is a palindrome
def is_binary_palindrome(x):
    
    # Convert to binary and remove '0b'
    binary = bin(x)[2:]  
    
    # Reverse and compare
    return binary == binary[::-1]  

if __name__ == "__main__":
    print("true" if is_binary_palindrome(9) else "false")
    print("true" if is_binary_palindrome(10) else "false")
C#
// C# program to check if binary representation
// of a number is palindrome
using System;

class GfG {
    // Function to check if binary representation is a palindrome
    public static bool IsBinaryPalindrome(int x) {
        string binary = Convert.ToString(x, 2); // Convert to binary
        char[] revBinary = binary.ToCharArray();
        Array.Reverse(revBinary); // Reverse the string
        
        return binary == new string(revBinary); // Check if palindrome
    }

    public static void Main() {
        Console.WriteLine(IsBinaryPalindrome(9) ? "true" : "false");
        Console.WriteLine(IsBinaryPalindrome(10) ? "true" : "false");
    }
}
JavaScript
// JavaScript program to check if binary representation 
// of a number is palindrome

// Function to check if binary representation is a palindrome
function isBinaryPalindrome(x) {
    let binary = x.toString(2); // Convert to binary
    let revBinary = binary.split("").reverse().join(""); // Reverse the string
    
    return binary === revBinary; // Check if palindrome
}

console.log(isBinaryPalindrome(9) ? "true" : "false");
console.log(isBinaryPalindrome(10) ? "true" : "false");

Output
true
false

Time Complexity: O(n), where n is the number of bits in the binary representation (at most 32).
Space Complexity: O(n) due to storing the binary string and its reverse.

Using OR to find Reverse – O(logn) Time and O(1) Space

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.

Steps to implement the above idea:

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

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if binary representation is a palindrome
bool isBinaryPalindrome(int x) {
    int rev = 0, temp = x;

    while (temp > 0) {
        rev = (rev << 1) | (temp & 1); // Append LSB to rev
        temp >>= 1; // Shift temp right
    }

    return x == rev; // Compare reversed with original
}

int main() {
    cout << (isBinaryPalindrome(9) ? "true" : "false") << endl;
    cout << (isBinaryPalindrome(10) ? "true" : "false") << endl;
    return 0;
}
Java
class GfG {
    // Function to check if binary representation is a palindrome
    static boolean isBinaryPalindrome(int x) {
        int rev = 0, temp = x;

        while (temp > 0) {
            rev = (rev << 1) | (temp & 1); // Append LSB to rev
            temp >>= 1; // Shift temp right
        }

        return x == rev; // Compare reversed with original
    }

    public static void main(String[] args) {
        System.out.println(isBinaryPalindrome(9) ? "true" : "false");
        System.out.println(isBinaryPalindrome(10) ? "true" : "false");
    }
}
Python
# Function to check if binary representation is a palindrome
def is_binary_palindrome(x):
    rev, temp = 0, x

    while temp > 0:
        rev = (rev << 1) | (temp & 1)  # Append LSB to rev
        temp >>= 1  # Shift temp right

    return x == rev  # Compare reversed with original

if __name__ == "__main__":
    print("true" if is_binary_palindrome(9) else "false")
    print("true" if is_binary_palindrome(10) else "false")
C#
using System;

class GfG {
    // Function to check if binary representation is a palindrome
    public static bool IsBinaryPalindrome(int x) {
        int rev = 0, temp = x;

        while (temp > 0) {
            rev = (rev << 1) | (temp & 1); // Append LSB to rev
            temp >>= 1; // Shift temp right
        }

        return x == rev; // Compare reversed with original
    }

    public static void Main() {
        Console.WriteLine(IsBinaryPalindrome(9) ? "true" : "false");
        Console.WriteLine(IsBinaryPalindrome(10) ? "true" : "false");
    }
}
JavaScript
// Function to check if binary representation is a palindrome
function isBinaryPalindrome(x) {
    let rev = 0, temp = x;

    while (temp > 0) {
        rev = (rev << 1) | (temp & 1); // Append LSB to rev
        temp >>= 1; // Shift temp right
    }

    return x === rev; // Compare reversed with original
}

console.log(isBinaryPalindrome(9) ? "true" : "false");
console.log(isBinaryPalindrome(10) ? "true" : "false");

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.



Next Article

Similar Reads