Given two numbers x and y, check whether the two numbers differ at one bit position only.
Example 1:
The binary representation of 7 is 0111 and of 5 is 0101. Here, only the second rightmost bit differs, while other bits remain the same.
Example 2:
The binary representation of 15 is 1111 and of 5 is 0101. Here, only the second and fourth rightmost bit differs, so the output is No.
The solution is simple and is as follows:
x and y.Refer to Check if a number is a power of two for different ways to implement step 2.
Let’s look at the code below:
public class Main {static boolean isPowerOfTwo(int n){return n != 0 && ((n & (n-1)) == 0);}static boolean oneBitPosDiffer(int x, int y){return isPowerOfTwo(x ^ y);}public static void main(String[] args) {int x = 5;int y = 15;boolean res = oneBitPosDiffer(x, y);if(res) System.out.println(x + " and " + y + " differ only by one bit");else System.out.println(x + " and " + y + " don't differ only by one bit");}}
isPowerOfTwo which checks if the given number is a power of two or not.oneBitPosDiffer which performs the bitwise XOR on the input numbers x and y. The result of the XOR operation is passed as an input to the isPowerOfTwo function.x.y.oneBitPosDiffer() with x and y as parameters.