Skip to content

Commit c929a2f

Browse files
committed
feat: Add OneBitDifference new algorithm with Junit tests
1 parent 2a518e3 commit c929a2f

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* This class provides a method to detect if two integers
5+
* differ by exactly one bit flip.
6+
*
7+
* Example:
8+
* 1 (0001) and 2 (0010) differ by exactly one bit flip.
9+
* 7 (0111) and 3 (0011) differ by exactly one bit flip.
10+
*
11+
* @author Hardvan
12+
*/
13+
public final class OneBitDifference {
14+
private OneBitDifference() {
15+
}
16+
17+
/**
18+
* Checks if two integers differ by exactly one bit.
19+
*
20+
* @param x the first integer
21+
* @param y the second integer
22+
* @return true if x and y differ by exactly one bit, false otherwise
23+
*/
24+
public static boolean differByOneBit(int x, int y) {
25+
if (x == y) {
26+
return false;
27+
}
28+
29+
int xor = x ^ y;
30+
return (xor & (xor - 1)) == 0;
31+
}
32+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.params.ParameterizedTest;
6+
import org.junit.jupiter.params.provider.CsvSource;
7+
8+
public class OneBitDifferenceTest {
9+
10+
@ParameterizedTest
11+
@CsvSource({"7, 5, true", "3, 2, true", "10, 8, true", "15, 15, false", "4, 1, false"})
12+
void testDifferByOneBit(int x, int y, boolean expected) {
13+
assertEquals(expected, OneBitDifference.differByOneBit(x, y));
14+
}
15+
}

0 commit comments

Comments
 (0)