Skip to content

Added ToggleKthBit algorithm in bitmanipulation with unit tests. The method toggles the K-th bit of a number using bitwise XOR. Includes an example and JavaDoc. #6299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.thealgorithms.bitmanipulation;


import java.util.ArrayList;
import java.util.List;

Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}
}
Original file line number Diff line number Diff line change
@@ -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
}
}