Add OneBitDifference algorithm (#5864)

This commit is contained in:
Hardik Pawar
2024-10-26 14:56:46 +05:30
committed by GitHub
parent 8551addbf2
commit cdf509fc06
3 changed files with 49 additions and 0 deletions

View File

@@ -0,0 +1,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;
}
}

View File

@@ -0,0 +1,15 @@
package com.thealgorithms.bitmanipulation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class OneBitDifferenceTest {
@ParameterizedTest
@CsvSource({"7, 5, true", "3, 2, true", "10, 8, true", "15, 15, false", "4, 1, false"})
void testDifferByOneBit(int x, int y, boolean expected) {
assertEquals(expected, OneBitDifference.differByOneBit(x, y));
}
}