Skip to content

Commit a7d140a

Browse files
authored
Add Set Kth Bit (TheAlgorithms#4990)
1 parent 7ece806 commit a7d140a

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/***
4+
* Sets the kth bit of a given integer to 1
5+
* e.g. setting 3rd bit in binary of 17 (binary 10001) gives 25 (binary 11001)
6+
* @author inishantjain
7+
*/
8+
9+
public class SetKthBit {
10+
/**
11+
* Sets the kth bit of a given integer.
12+
*
13+
* @param num The original integer.
14+
* @param k The position of the bit to set (0-based index).
15+
* @return The integer with the kth bit set.
16+
*/
17+
public static int setKthBit(int num, int k) {
18+
int mask = 1 << k;
19+
num = num | mask;
20+
return num;
21+
}
22+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class SetKthBitTest {
8+
9+
@Test
10+
void testSetKthBit() {
11+
// Test case: Setting the 0th bit in 5 (binary 101)
12+
assertEquals(5, SetKthBit.setKthBit(5, 0));
13+
14+
// Test case: Setting the 2nd bit in 10 (binary 1010)
15+
assertEquals(14, SetKthBit.setKthBit(10, 2));
16+
17+
// Test case: Setting the 3rd bit in 15 (binary 1111)
18+
assertEquals(15, SetKthBit.setKthBit(15, 3));
19+
20+
// Test case: Setting the 1st bit in 0 (binary 0)
21+
assertEquals(2, SetKthBit.setKthBit(0, 1));
22+
}
23+
}

0 commit comments

Comments
 (0)