|
1 | 1 | package com.thealgorithms.bitmanipulation; |
2 | 2 |
|
3 | 3 | /** |
4 | | - * Swap every pair of adjacent bits of a given number. |
5 | | - * @author Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999) |
| 4 | + * A utility class to swap every pair of adjacent bits in a given integer. |
| 5 | + * This operation shifts the even-positioned bits to odd positions and vice versa. |
| 6 | + * |
| 7 | + * Example: |
| 8 | + * - Input: 2 (binary: `10`) → Output: 1 (binary: `01`) |
| 9 | + * - Input: 43 (binary: `101011`) → Output: 23 (binary: `010111`) |
| 10 | + * |
| 11 | + * **Explanation of the Algorithm:** |
| 12 | + * 1. Mask even-positioned bits: Using `0xAAAAAAAA` (binary: `101010...`), |
| 13 | + * which selects bits in even positions. |
| 14 | + * 2. Mask odd-positioned bits: Using `0x55555555` (binary: `010101...`), |
| 15 | + * which selects bits in odd positions. |
| 16 | + * 3. Shift bits: |
| 17 | + * - Right-shift even-positioned bits by 1 to move them to odd positions. |
| 18 | + * - Left-shift odd-positioned bits by 1 to move them to even positions. |
| 19 | + * 4. Combine both shifted results using bitwise OR (`|`) to produce the final result. |
| 20 | + * |
| 21 | + * Use Case: This algorithm can be useful in applications involving low-level bit manipulation, |
| 22 | + * such as encoding, data compression, or cryptographic transformations. |
| 23 | + * |
| 24 | + * Time Complexity: O(1) (constant time, since operations are bitwise). |
| 25 | + * |
| 26 | + * Author: Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999) |
6 | 27 | */ |
7 | | - |
8 | 28 | public final class SwapAdjacentBits { |
9 | 29 | private SwapAdjacentBits() { |
10 | 30 | } |
11 | 31 |
|
| 32 | + /** |
| 33 | + * Swaps every pair of adjacent bits of a given integer. |
| 34 | + * Steps: |
| 35 | + * 1. Mask the even-positioned bits. |
| 36 | + * 2. Mask the odd-positioned bits. |
| 37 | + * 3. Shift the even bits to the right and the odd bits to the left. |
| 38 | + * 4. Combine the shifted bits. |
| 39 | + * |
| 40 | + * @param num the integer whose bits are to be swapped |
| 41 | + * @return the integer after swapping every pair of adjacent bits |
| 42 | + */ |
12 | 43 | public static int swapAdjacentBits(int num) { |
13 | | - // mask the even bits (0xAAAAAAAA => 10101010...) |
14 | 44 | int evenBits = num & 0xAAAAAAAA; |
15 | | - |
16 | | - // mask the odd bits (0x55555555 => 01010101...) |
17 | 45 | int oddBits = num & 0x55555555; |
18 | | - |
19 | | - // right shift even bits and left shift odd bits |
20 | 46 | evenBits >>= 1; |
21 | 47 | oddBits <<= 1; |
22 | | - |
23 | | - // combine shifted bits |
24 | 48 | return evenBits | oddBits; |
25 | 49 | } |
26 | 50 | } |
0 commit comments