Write Java program to Count the number of bits to be flipped to convert a number to another number


This program takes two integers as input and counts the number of bits that need to be flipped in order to convert one integer into another. The program uses bitwise operators to compare the binary representation of the two integers. It starts by comparing the least significant bit of each integer, and then shifts both integers to the right by one bit. This process continues until both integers become 0.

If the least significant bit of the two integers are different, it increments a counter variable. At the end of the program, the counter variable represents the number of bits that need to be flipped. Overall, this program is useful for determining the difference between two binary values and can be applied in various fields such as cryptography, data compression, and data transmission.

Source Code

import java.util.Scanner;
public class Count_NumberBits
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
 
		int n1 = 0;
		int n2 = 0;
 
		int cnt = 0;
		int lsb1 = 0;
		int lsb2 = 0;
 
		System.out.printf("Enter the Number 1 : ");
		n1 = input.nextInt();
 
		System.out.printf("Enter the Number 2 : ");
		n2 = input.nextInt();
 
		while ((n1 > 0) || (n2 > 0))
		{
			lsb1 = n1 & 1;
			lsb2 = n2 & 1;
 
			if (lsb1 != lsb2)
				cnt++;
 
			n1 = n1 >> 1;
			n2 = n2 >> 1;
		}
		System.out.println("Number of bits flipped : "+ cnt);
	}
}

Output

Enter the Number 1 : 10
Enter the Number 2 : 50
Number of bits flipped : 3

Example Programs