File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
main/java/com/thealgorithms/bitmanipulation
test/java/com/thealgorithms/bitmanipulation Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments