Skip to content

Commit 6535d47

Browse files
Add SwapAdjacentBits algorithm (#5634)
1 parent c0f3524 commit 6535d47

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* Swap every pair of adjacent bits of a given number.
5+
* @author Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999)
6+
*/
7+
8+
public final class SwapAdjacentBits {
9+
private SwapAdjacentBits() {
10+
}
11+
12+
public static int swapAdjacentBits(int num) {
13+
// mask the even bits (0xAAAAAAAA => 10101010...)
14+
int evenBits = num & 0xAAAAAAAA;
15+
16+
// mask the odd bits (0x55555555 => 01010101...)
17+
int oddBits = num & 0x55555555;
18+
19+
// right shift even bits and left shift odd bits
20+
evenBits >>= 1;
21+
oddBits <<= 1;
22+
23+
// combine shifted bits
24+
return evenBits | oddBits;
25+
}
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
class SwapAdjacentBitsTest {
9+
10+
@ParameterizedTest
11+
@CsvSource({
12+
"2, 1", // 2 (10 in binary) should become 1 (01 in binary)
13+
"43, 23", // 43 should become 23
14+
"153, 102", // 153 should become 102
15+
"15, 15", // 15 (1111) remains 15 (1111)
16+
"0, 0" // 0 (0000) remains 0 (0000)
17+
})
18+
void
19+
testSwapAdjacentBits(int input, int expected) {
20+
assertEquals(expected, SwapAdjacentBits.swapAdjacentBits(input));
21+
}
22+
}

0 commit comments

Comments
 (0)