diff --git a/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java b/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java new file mode 100644 index 000000000..933dec565 --- /dev/null +++ b/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java @@ -0,0 +1,26 @@ +package com.thealgorithms.bitmanipulation; + +/** + * Swap every pair of adjacent bits of a given number. + * @author Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999) + */ + +public final class SwapAdjacentBits { + private SwapAdjacentBits() { + } + + public static int swapAdjacentBits(int num) { + // mask the even bits (0xAAAAAAAA => 10101010...) + int evenBits = num & 0xAAAAAAAA; + + // mask the odd bits (0x55555555 => 01010101...) + int oddBits = num & 0x55555555; + + // right shift even bits and left shift odd bits + evenBits >>= 1; + oddBits <<= 1; + + // combine shifted bits + return evenBits | oddBits; + } +} diff --git a/src/test/java/com/thealgorithms/bitmanipulation/SwapAdjacentBitsTest.java b/src/test/java/com/thealgorithms/bitmanipulation/SwapAdjacentBitsTest.java new file mode 100644 index 000000000..67c986136 --- /dev/null +++ b/src/test/java/com/thealgorithms/bitmanipulation/SwapAdjacentBitsTest.java @@ -0,0 +1,22 @@ +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; + +class SwapAdjacentBitsTest { + + @ParameterizedTest + @CsvSource({ + "2, 1", // 2 (10 in binary) should become 1 (01 in binary) + "43, 23", // 43 should become 23 + "153, 102", // 153 should become 102 + "15, 15", // 15 (1111) remains 15 (1111) + "0, 0" // 0 (0000) remains 0 (0000) + }) + void + testSwapAdjacentBits(int input, int expected) { + assertEquals(expected, SwapAdjacentBits.swapAdjacentBits(input)); + } +}