File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed
main/java/com/thealgorithms/bitmanipulation
test/java/com/thealgorithms/bitmanipulation Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .thealgorithms .bitmanipulation ;
2+
3+ public class ClearLeftmostSetBit {
4+
5+ /**
6+ * Clears the leftmost set bit (1) of a given number.
7+ * Step 1: Find the position of the leftmost set bit
8+ * Step 2: Create a mask with all bits set except for the leftmost set bit
9+ * Step 3: Clear the leftmost set bit using AND with the mask
10+ *
11+ * @param num The input number.
12+ * @return The number after clearing the leftmost set bit.
13+ */
14+ public static int clearLeftmostSetBit (int num ) {
15+ int pos = 0 ;
16+ int temp = num ;
17+ while (temp > 0 ) {
18+ temp >>= 1 ;
19+ pos ++;
20+ }
21+
22+ int mask = ~(1 << (pos - 1 ));
23+ return num & mask ;
24+ }
25+ }
Original file line number Diff line number Diff line change 1+ package com .thealgorithms .bitmanipulation ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertEquals ;
4+
5+ import org .junit .jupiter .api .Test ;
6+
7+ public class ClearLeftmostSetBitTest {
8+
9+ @ Test
10+ public void testClearLeftmostSetBit () {
11+ assertEquals (10 , ClearLeftmostSetBit .clearLeftmostSetBit (26 )); // 11010 -> 01010
12+ assertEquals (0 , ClearLeftmostSetBit .clearLeftmostSetBit (1 )); // 1 -> 0
13+ assertEquals (3 , ClearLeftmostSetBit .clearLeftmostSetBit (7 )); // 111 -> 011
14+ assertEquals (2 , ClearLeftmostSetBit .clearLeftmostSetBit (6 )); // 0110 -> 0010
15+ }
16+ }
You can’t perform that action at this time.
0 commit comments