Reverse the binary representation of a number.

Objective: Write a program to Reverse the binary representation of a number

Example:

Input : 30
Output : 15

Explanation:

binary representation of 30 is : 11110
reverse of binary representation : 01111
decimal of reversed binary representation is : 15

Input: A Number

Output: Decimal of reversed binary representation of a number.

Approach:

  • Initialize int res =0
  • Now from a number , take one bit at a time
  • take AND of that bit with 1 and then OR with res and store it in res
  • make right shift in number by 1
  • make left shift in res by 1
Reverse Binray representation of a Decimal
Reverse Binray representation of a Decimal

Complete Code:

public class BinaryRotate {
public int rotateBinary(int number){
int res = 0;
while(number>0){
res=res<<1;
res = res|(number & 1);
number=number>>1;
}
return res;
}
public static void main(String args[]){
int x =30;
BinaryRotate b = new BinaryRotate();
System.out.println("Binary rotation of "+ x + " is : " + b.rotateBinary(x));
}
}

view raw
BinaryRotate.java
hosted with ❤ by GitHub

Output:

Binary rotation of 30 is : 15