diff --git a/src/main/java/com/thealgorithms/bitmanipulation/GenerateSubsets.java b/src/main/java/com/thealgorithms/bitmanipulation/GenerateSubsets.java index f1b812495c1b..11d82a4d2009 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/GenerateSubsets.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/GenerateSubsets.java @@ -1,5 +1,6 @@ package com.thealgorithms.bitmanipulation; + import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/thealgorithms/bitmanipulation/ToggleKthBit.java b/src/main/java/com/thealgorithms/bitmanipulation/ToggleKthBit.java new file mode 100644 index 000000000000..ff9413313749 --- /dev/null +++ b/src/main/java/com/thealgorithms/bitmanipulation/ToggleKthBit.java @@ -0,0 +1,30 @@ +package com.thealgorithms.bitmanipulation; + +/** + * The ToggleKthBit class provides a method to toggle the K-th bit of a given number. + * + * Toggling means: if the K-th bit is 1, it becomes 0; if it's 0, it becomes 1. + * + * Example: + * Input: n = 10 (1010 in binary), k = 1 + * Output: 8 (1000 in binary) + * + * @author Rahul + */ +public final class ToggleKthBit { + + private ToggleKthBit() { + // Utility class, no need to instantiate + } + + /** + * Toggles the K-th bit (0-based index from right) of a number. + * + * @param n the number to toggle the bit in + * @param k the position of the bit to toggle (0-based) + * @return the number after toggling the K-th bit + */ + public static int toggleKthBit(int n, int k) { + return n ^ (1 << k); + } +} diff --git a/src/test/java/com/thealgorithms/bitmanipulation/ToggleKthBitTest.java b/src/test/java/com/thealgorithms/bitmanipulation/ToggleKthBitTest.java new file mode 100644 index 000000000000..f913022517ed --- /dev/null +++ b/src/test/java/com/thealgorithms/bitmanipulation/ToggleKthBitTest.java @@ -0,0 +1,15 @@ +package com.thealgorithms.bitmanipulation; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +public class ToggleKthBitTest { + + @Test + public void testToggleKthBit() { + assertEquals(8, ToggleKthBit.toggleKthBit(10, 1)); // 1010 ^ (1<<1) = 1000 + assertEquals(14, ToggleKthBit.toggleKthBit(10, 2)); // 1010 ^ (1<<2) = 1110 + assertEquals(2, ToggleKthBit.toggleKthBit(0, 1)); // 0000 ^ (1<<1) = 0010 + assertEquals(0, ToggleKthBit.toggleKthBit(1, 0)); // 0001 ^ (1<<0) = 0000 + } +}