
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse Bits of a Positive Integer in Java
The bits of an integer number can be reversed to obtain another number. An example of this is given as follows −
Number = 11 Binary representation = 1011 Reversed binary representation = 1101 Reversed number = 13
A program that demonstrates this is given as follows −
Example
public class Example { public static void main(String[] args) { int num = 14; int n = num; int rev = 0; while (num > 0) { rev <<= 1; if ((int)(num & 1) == 1) rev ^= 1; num >>= 1; } System.out.println("The original number is: " + n); System.out.println("The number with reversed bits is: " + rev); } }
Output
The original number is: 14 The number with reversed bits is: 7
Now let us understand the above program.
The number is defined. Then a while loop is used to reverse the bits of the number. The code snippet that demonstrates this is given as follows −
int num = 14; int n = num; int rev = 0; while (num > 0) { rev <<= 1; if ((int)(num & 1) == 1) rev ^= 1; num >>= 1; }
Finally, the number, as well as the reversed number, are displayed. The code snippet that demonstrates this is given as follows −
System.out.println("The original number is: " + n); System.out.println("The number with reversed bits is: " + rev);
Advertisements