Skip to content

Commit 05ceb19

Browse files
Bit swap enhancement (#6577)
1 parent 5e9d9f7 commit 05ceb19

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,15 @@ private BitSwap() {
1717
* @return The modified value with swapped bits
1818
* @throws IllegalArgumentException if either position is negative or ≥ 32
1919
*/
20+
2021
public static int bitSwap(int data, final int posA, final int posB) {
2122
if (posA < 0 || posA >= Integer.SIZE || posB < 0 || posB >= Integer.SIZE) {
2223
throw new IllegalArgumentException("Bit positions must be between 0 and 31");
2324
}
2425

25-
if (SingleBitOperations.getBit(data, posA) != SingleBitOperations.getBit(data, posB)) {
26+
boolean bitA = ((data >> posA) & 1) != 0;
27+
boolean bitB = ((data >> posB) & 1) != 0;
28+
if (bitA != bitB) {
2629
data ^= (1 << posA) ^ (1 << posB);
2730
}
2831
return data;

0 commit comments

Comments
 (0)