Write Java program to print bits that need to be flipped to convert a number to another number


The program starts by using a Scanner object to read in two integers from the user: n1 and n2. It then initializes some variables: bit_num to store the current bit position being checked, lsb1 to store the least significant bit of n1, and lsb2 to store the least significant bit of n2.

The program then enters a while loop that continues as long as either n1 or n2 is greater than 0. Inside the loop, it checks the least significant bits of n1 and n2 using the bitwise AND operator with the number 1. If the least significant bits are different, then the program prints out the current bit_num as a bit position where the binary representations of n1 and n2 differ.

Finally, the program right-shifts n1 and n2 by 1 bit, increments bit_num, and continues the loop until all bits in both n1 and n2 have been checked.

Overall, this program correctly finds the bit positions where the binary representations of n1 and n2 differ. However, it assumes that both n1 and n2 are non-negative integers. If negative integers are used as input, the program will not work as expected.

Source Code

import java.util.Scanner;
public class Convert_Number
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
 
		int n1 = 0;
		int n2 = 0;
 
		int bit_num = 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();
 
		System.out.printf("Bits needs to be Changed are :");
 
		while ((n1 > 0) || (n2 > 0))
		{
			lsb1 = n1 & 1;
			lsb2 = n2 & 1;
 
			if (lsb1 != lsb2)
			{
				System.out.printf("%d ", bit_num);
			}
 
			n1 = n1 >> 1;
			n2 = n2 >> 1;
 
			bit_num++;
		}
	}
}

Output

Enter the Number 1 : 23
Enter the Number 2 : 45
Bits needs to be Changed are :1 3 4 5

Example Programs