File tree 2 files changed +47
-0
lines changed
main/java/com/thealgorithms/bitmanipulation
test/java/com/thealgorithms/bitmanipulation
2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change
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 number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments