Skip to content

Commit 8ef5e80

Browse files
author
prayas7102
committed
clearLowestSetBit added with tests
1 parent 611dfab commit 8ef5e80

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java

+11
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,15 @@ public static int isolateLowestSetBit(int n) {
2020
// Isolate the lowest set bit using n & -n
2121
return n & -n;
2222
}
23+
/**
24+
* Clears the lowest set bit of the given number.
25+
* For example, if n = 18 (binary: 10010), the result will be 16 (binary: 10000).
26+
*
27+
* @param n the number whose lowest set bit will be cleared
28+
* @return the number after clearing its lowest set bit
29+
*/
30+
public static int clearLowestSetBit(int n) {
31+
// Clear the lowest set bit using n & (n - 1)
32+
return n & (n - 1);
33+
}
2334
}

src/test/java/com/thealgorithms/bitmanipulation/LowestSetBitTest.java

+31
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,35 @@ void testLowestSetBitWithLargeNumber() {
5252
// Test with a large number
5353
assertEquals(64, LowestSetBit.isolateLowestSetBit(448)); // 448 in binary: 111000000, lowest bit is 64
5454
}
55+
56+
@Test
57+
void testClearLowestSetBitFor18() {
58+
// n = 18 (binary: 10010), expected result = 16 (binary: 10000)
59+
assertEquals(16, LowestSetBit.clearLowestSetBit(18));
60+
}
61+
62+
@Test
63+
void testClearLowestSetBitFor10() {
64+
// n = 10 (binary: 1010), expected result = 8 (binary: 1000)
65+
assertEquals(8, LowestSetBit.clearLowestSetBit(10));
66+
}
67+
68+
@Test
69+
void testClearLowestSetBitFor7() {
70+
// n = 7 (binary: 0111), expected result = 6 (binary: 0110)
71+
assertEquals(6, LowestSetBit.clearLowestSetBit(7));
72+
}
73+
74+
@Test
75+
void testClearLowestSetBitFor0() {
76+
// n = 0 (binary: 0000), no set bits to clear, expected result = 0
77+
assertEquals(0, LowestSetBit.clearLowestSetBit(0));
78+
}
79+
80+
@Test
81+
void testClearLowestSetBitForNegativeNumber() {
82+
// Test negative number to see how it behaves with two's complement
83+
// n = -1 (binary: all 1s in two's complement), expected result = -2 (clearing lowest set bit)
84+
assertEquals(-2, LowestSetBit.clearLowestSetBit(-1));
85+
}
5586
}

0 commit comments

Comments
 (0)