Skip to content

Commit 7aeb2df

Browse files
authored
Update BitSwap.java
removed the external getBit() method and replaced it with direct bitwise operations to check and swap bits more efficiently.
1 parent e499d3b commit 7aeb2df

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@ private BitSwap() {
77
* @brief Swaps the bits at the position posA and posB from data
88
*/
99
public static int bitSwap(int data, final int posA, final int posB) {
10-
if (SingleBitOperations.getBit(data, posA) != SingleBitOperations.getBit(data, posB)) {
11-
data ^= (1 << posA) ^ (1 << posB);
10+
// Check if the bits at posA and posB are different
11+
if (((data >> posA) & 1) != ((data >> posB) & 1)) {
12+
// Swap the bits using XOR
13+
data ^= (1 << posA) | (1 << posB);
1214
}
1315
return data;
1416
}

0 commit comments

Comments
 (0)