forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOneBitDifference.java
More file actions
32 lines (29 loc) · 785 Bytes
/
OneBitDifference.java
File metadata and controls
32 lines (29 loc) · 785 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.thealgorithms.bitmanipulation;
/**
* This class provides a method to detect if two integers
* differ by exactly one bit flip.
*
* Example:
* 1 (0001) and 2 (0010) differ by exactly one bit flip.
* 7 (0111) and 3 (0011) differ by exactly one bit flip.
*
* @author Hardvan
*/
public final class OneBitDifference {
private OneBitDifference() {
}
/**
* Checks if two integers differ by exactly one bit.
*
* @param x the first integer
* @param y the second integer
* @return true if x and y differ by exactly one bit, false otherwise
*/
public static boolean differByOneBit(int x, int y) {
if (x == y) {
return false;
}
int xor = x ^ y;
return (xor & (xor - 1)) == 0;
}
}