Skip to content

Add Set Kth Bit #4990

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

Merged
merged 1 commit into from
Jan 2, 2024
Merged
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
22 changes: 22 additions & 0 deletions src/main/java/com/thealgorithms/bitmanipulation/SetKthBit.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.thealgorithms.bitmanipulation;

/***
* Sets the kth bit of a given integer to 1
* e.g. setting 3rd bit in binary of 17 (binary 10001) gives 25 (binary 11001)
* @author inishantjain
*/

public class SetKthBit {
/**
* Sets the kth bit of a given integer.
*
* @param num The original integer.
* @param k The position of the bit to set (0-based index).
* @return The integer with the kth bit set.
*/
public static int setKthBit(int num, int k) {
int mask = 1 << k;
num = num | mask;
return num;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.thealgorithms.bitmanipulation;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class SetKthBitTest {

@Test
void testSetKthBit() {
// Test case: Setting the 0th bit in 5 (binary 101)
assertEquals(5, SetKthBit.setKthBit(5, 0));

// Test case: Setting the 2nd bit in 10 (binary 1010)
assertEquals(14, SetKthBit.setKthBit(10, 2));

// Test case: Setting the 3rd bit in 15 (binary 1111)
assertEquals(15, SetKthBit.setKthBit(15, 3));

// Test case: Setting the 1st bit in 0 (binary 0)
assertEquals(2, SetKthBit.setKthBit(0, 1));
}
}