Skip to content

Commit 5aca060

Browse files
committed
feat: Add ParityCheck new algorithm with Junit tests
1 parent 90d20b3 commit 5aca060

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* The ParityCheck class provides a method to check the parity of a given number.
5+
* <p>
6+
* Parity is a mathematical term that describes the property of an integer's binary representation.
7+
* The parity of a binary number is the number of 1s in its binary representation.
8+
* If the number of 1s is even, the parity is even; otherwise, it is odd.
9+
* <p>
10+
* For example, the binary representation of 5 is 101, which has two 1s, so the parity of 5 is even.
11+
* The binary representation of 6 is 110, which has two 1s, so the parity of 6 is even.
12+
* The binary representation of 7 is 111, which has three 1s, so the parity of 7 is odd.
13+
*
14+
* @author Hardvan
15+
*/
16+
public final class ParityCheck {
17+
private ParityCheck() {
18+
}
19+
20+
/**
21+
* This method checks the parity of the given number.
22+
*
23+
* @param n the number to check the parity of
24+
* @return true if the number has even parity, false otherwise
25+
*/
26+
public static boolean checkParity(int n) {
27+
int count = 0;
28+
while (n > 0) {
29+
count += n & 1;
30+
n >>= 1;
31+
}
32+
return count % 2 == 0;
33+
}
34+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertFalse;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
public class ParityCheckTest {
9+
10+
@Test
11+
public void testIsOddParity() {
12+
assertTrue(ParityCheck.checkParity(5)); // 101 has 2 ones (even parity)
13+
assertFalse(ParityCheck.checkParity(7)); // 111 has 3 ones (odd parity)
14+
assertFalse(ParityCheck.checkParity(8)); // 1000 has 1 one (odd parity)
15+
}
16+
}

0 commit comments

Comments
 (0)