Bit swap (#4770)
* Create BitSwap.java * Create BitSwapTest.java * Update BitSwap.java * Update BitSwap.java * Update BitSwapTest.java * Update BitSwap.java * Update BitSwap.java * Update BitSwapTest.java * Update BitSwapTest.java * Update src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * Update src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * Update BitSwap.java * Update BitSwap.java * Update BitSwap.java * Update src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * Update src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * Update src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> * style: remove redundant blank line --------- Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
This commit is contained in:
parent
24a8223062
commit
48ae88f09d
15
src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java
Normal file
15
src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java
Normal file
@ -0,0 +1,15 @@
|
||||
package com.thealgorithms.bitmanipulation;
|
||||
|
||||
public final class BitSwap {
|
||||
private BitSwap() {
|
||||
}
|
||||
/*
|
||||
* @brief Swaps the bits at the position posA and posB from data
|
||||
*/
|
||||
public static int bitSwap(int data, final int posA, final int posB) {
|
||||
if (SingleBitOperations.getBit(data, posA) != SingleBitOperations.getBit(data, posB)) {
|
||||
data ^= (1 << posA) ^ (1 << posB);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.thealgorithms.bitmanipulation;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
public class BitSwapTest {
|
||||
@Test
|
||||
void testHighestSetBit() {
|
||||
assertEquals(3, BitSwap.bitSwap(3, 0, 1));
|
||||
assertEquals(5, BitSwap.bitSwap(6, 0, 1));
|
||||
assertEquals(7, BitSwap.bitSwap(7, 1, 1));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user