Skip to content

Commit 0027f57

Browse files
committed
feat: Add ClearLeftmostSetBit new algorithm with Junit tests
1 parent 90d20b3 commit 0027f57

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
}

0 commit comments

Comments
 (0)