Skip to content

Commit def7a0b

Browse files
Added algorithm for Swaping Adjacent Bits using Bit Manipulation
1 parent 9fb8192 commit def7a0b

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 26 additions & 0 deletions
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+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class SwapAdjacentBitsTest {
8+
9+
@Test
10+
void testSwapAdjacentBits() {
11+
assertEquals(1, SwapAdjacentBits.swapAdjacentBits(2));
12+
13+
assertEquals(23, SwapAdjacentBits.swapAdjacentBits(43));
14+
15+
assertEquals(102, SwapAdjacentBits.swapAdjacentBits(153));
16+
17+
assertEquals(15, SwapAdjacentBits.swapAdjacentBits(15));
18+
19+
assertEquals(0, SwapAdjacentBits.swapAdjacentBits(0));
20+
}
21+
}

0 commit comments

Comments
 (0)