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

Upasana | August 05, 2019 | 1 min read | 103 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. Write a program to swap two numbers in Java
  2. find single repeating number from a big array
  3. Hibernate & Spring Data JPA interview questions
  4. There is no PasswordEncoder mapped for the id
  5. Relative efficiency of Algorithms using Big O Notation
  6. What is difference between Primary key and Unique Key
  7. Pangram checker in java

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.