Skip to content

Commit 332a135

Browse files
committed
feat: add ToggleKthBit algorithm with test
1 parent a21abe6 commit 332a135

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* The ToggleKthBit class provides a method to toggle the K-th bit of a given number.
5+
*
6+
* Toggling means: if the K-th bit is 1, it becomes 0; if it's 0, it becomes 1.
7+
*
8+
* Example:
9+
* Input: n = 10 (1010 in binary), k = 1
10+
* Output: 8 (1000 in binary)
11+
*
12+
* @author Rahul
13+
*/
14+
public final class ToggleKthBit {
15+
16+
private ToggleKthBit() {
17+
// Utility class, no need to instantiate
18+
}
19+
20+
/**
21+
* Toggles the K-th bit (0-based index from right) of a number.
22+
*
23+
* @param n the number to toggle the bit in
24+
* @param k the position of the bit to toggle (0-based)
25+
* @return the number after toggling the K-th bit
26+
*/
27+
public static int toggleKthBit(int n, int k) {
28+
return n ^ (1 << k);
29+
}
30+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import org.junit.jupiter.api.Test;
5+
6+
public class ToggleKthBitTest {
7+
8+
@Test
9+
public void testToggleKthBit() {
10+
assertEquals(8, ToggleKthBit.toggleKthBit(10, 1)); // 1010 ^ (1<<1) = 1000
11+
assertEquals(14, ToggleKthBit.toggleKthBit(10, 2)); // 1010 ^ (1<<2) = 1110
12+
assertEquals(2, ToggleKthBit.toggleKthBit(0, 1)); // 0000 ^ (1<<1) = 0010
13+
assertEquals(0, ToggleKthBit.toggleKthBit(1, 0)); // 0001 ^ (1<<0) = 0000
14+
}
15+
}

0 commit comments

Comments
 (0)