Interview Question:
Write a Java method that will return the number of bits that will need to be changed in order to convert an integer, X, into another integer, Y and vice versa. The method should accept two different integers as input.
Answer:
The key here is to use XOR operation z = x ^ y; to get the bit difference between them, then count the bit set in the result z.
Write a Java method that will return the number of bits that will need to be changed in order to convert an integer, X, into another integer, Y and vice versa. The method should accept two different integers as input.
Answer:
The key here is to use XOR operation z = x ^ y; to get the bit difference between them, then count the bit set in the result z.
public static int bitConvertBetweenTwoTintegers(int x, int y) { // XOR x and y to get the bit difference between x and y int z = x ^ y; return numberofBits(z); } public static int numberofBits(int x) { int n = 0; while (x != 0) { n = n + 1; // clear the least significant bit set x = x & (x - 1); } return n; }