Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.thealgorithms.bitmanipulation;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

class SwapAdjacentBitsTest {

@Test
void testSwapAdjacentBits() {
assertEquals(1, SwapAdjacentBits.swapAdjacentBits(2));

assertEquals(23, SwapAdjacentBits.swapAdjacentBits(43));

assertEquals(102, SwapAdjacentBits.swapAdjacentBits(153));

assertEquals(15, SwapAdjacentBits.swapAdjacentBits(15));

assertEquals(0, SwapAdjacentBits.swapAdjacentBits(0));
}
}