How to print the bits that need to be flipped to convert a number to another number in Java

1 Answer

0 votes
public class MyClass {
    private static void printNeedToBeFlippedBits(int num1, int num2) {
	    int bitNum = 0;
	    int lsb1 = 0;
	    int lsb2 = 0;

	    while ((num1 > 0) || (num2 > 0)) {
		    lsb1 = num1 & 1;
		    lsb2 = num2 & 1;

		    if (lsb1 != lsb2) {
			    System.out.print(bitNum + " " );
		    }

		    num1 = num1 >> 1;
		    num2 = num2 >> 1;

		    bitNum++;
	    }
    }
    
    public static void main(String args[]) {
        int num1 = 2;  // 00000010
	    int num2 = 17; // 00010001
	    printNeedToBeFlippedBits(num1, num2);

	    System.out.print("\n");

	    num1 = 3;   // 00000011
	    num2 = 221; // 11011101
	    printNeedToBeFlippedBits(num1, num2);
    }
}





/*
run:
  
0 1 4 
1 2 3 4 6 7 
      
*/

 



answered Dec 25, 2023 by avibootz
edited Dec 25, 2023 by avibootz
...