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.

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

Upasana | August 05, 2019 | 1 min read | 103 views

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.

##### Top articles in this category:

- Write a program to swap two numbers in Java
- find single repeating number from a big array
- Hibernate & Spring Data JPA interview questions
- There is no PasswordEncoder mapped for the id
- Relative efficiency of Algorithms using Big O Notation
- What is difference between Primary key and Unique Key
- Pangram checker in java

###### Recommended books for interview preparation:

Book you may be interested in..

Book you may be interested in..