Reverse the bits of a number and check if the number is palindrome or not

Carvia Tech | August 05, 2019 | 1 min read | 82 views

Palindrome - Wiki definition

A palindrome is a word, number, or other sequence of characters which reads the same backward as forward, such as madam, racecar or 101 in binary etc.

We need a mechanism to reverse all the bits of the given input number and compare if both the number looks same after bit reversal.

The following Java code does the same:

Bitwise Palindrome
public static void main(String[] args) {
        int originalNumber = 9;
        long numBitsReversed = reverseBitsV1(originalNumber);
        long result = originalNumber ^ numBitsReversed; (1)
        if (result == 0) {
            System.out.println("Number is Palindrome");
        } else {
            System.out.println("Number is not Palindrome");

public static int reverseBitsV1(int number) {
    int reverse = 0;
    while (number != 0) {
        reverse <<= 1;  //left shift `reverse` by 1
        reverse |= (number & 1);   //Copy the rightmost bit of `number` into `reverse`
        number >>= 1;  //right shift `number` by 1
    return reverse;
1 Just comparing of both numbers are same or not

Slightly different variant of reverse bit could be below code:

public static int reverseBitsV2(int number) {
    int reverse = 0;
    //Traversing bits of 'number' from the right and pushing it into left of `reverse` number
    while (number > 0) {
        reverse <<= 1; //Bitwise left shift 'reverse' by 1
        if ((number & 1) == 1) //if current bit is '1'
            reverse ^= 1; //Bitwise right shift 'number' by 1
        number >>= 1;
    return reverse;

Functionality wise both are same.

Buy my ebook for complete question bank

Most of these questions has been answered in my eBook "Cracking the Core Java Interview" updated on June 2018, that you can buy from this link:

Buy from Shunya (DRM Free PDF download with updates)

Top articles in this category:
  1. ION Trading Java Interview Questions
  2. Cracking core java interviews - question bank
  3. Goldman Sachs Java Interview Questions for Senior Developer
  4. Java Concurrency Interview Questions
  5. Morgan Stanley Java Interview Questions
  6. Hibernate & Spring Data JPA interview questions
  7. Multi-threading Java Interview Questions for Investment Bank

Find more on this topic:
Java Interviews image
Java Interviews

Interview - Product Companies, eCommerce Companies, Investment Banking, Healthcare Industry, Service Companies and Startups.

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info