Skip to content

Commit 772ff2f

Browse files
authored
Merge branch 'master' into fix/pronic-number-overflow
2 parents fb44fad + f4d6708 commit 772ff2f

2 files changed

Lines changed: 16 additions & 4 deletions

File tree

‎src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
/**
44
* Gray code is a binary numeral system where two successive values differ in only one bit.
5-
* This is a simple conversion between binary and Gray code.
5+
* Each input and result is treated as a 32-bit pattern, including the sign bit.
66
* Example:
77
* 7 -> 0111 -> 0100 -> 4
88
* 4 -> 0100 -> 0111 -> 7
@@ -24,7 +24,7 @@ private GrayCodeConversion() {
2424
* @return The corresponding Gray code.
2525
*/
2626
public static int binaryToGray(int num) {
27-
return num ^ (num >> 1);
27+
return num ^ (num >>> 1);
2828
}
2929

3030
/**
@@ -35,8 +35,8 @@ public static int binaryToGray(int num) {
3535
*/
3636
public static int grayToBinary(int gray) {
3737
int binary = gray;
38-
while (gray > 0) {
39-
gray >>= 1;
38+
while (gray != 0) {
39+
gray >>>= 1;
4040
binary ^= gray;
4141
}
4242
return binary;

‎src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,18 @@ public void testGrayToBinary() {
2020
assertEquals(1, GrayCodeConversion.grayToBinary(1)); // 001 -> 001
2121
}
2222

23+
@Test
24+
public void testBinaryToGrayWithHighBitSet() {
25+
assertEquals(0x80000000, GrayCodeConversion.binaryToGray(0xFFFFFFFF));
26+
assertEquals(0xC0000000, GrayCodeConversion.binaryToGray(0x80000000));
27+
}
28+
29+
@Test
30+
public void testGrayToBinaryWithHighBitSet() {
31+
assertEquals(0xFFFFFFFF, GrayCodeConversion.grayToBinary(0x80000000));
32+
assertEquals(0x80000000, GrayCodeConversion.grayToBinary(0xC0000000));
33+
}
34+
2335
@Test
2436
public void testBinaryGrayCycle() {
2537
int binary = 9; // 1001 in binary

0 commit comments

Comments
 (0)