Skip to content

Commit 9d2cc53

Browse files
author
prayas7102
committed
LowestSetBit implementation and tests added
1 parent be8df21 commit 9d2cc53

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
public class LowestSetBit {
4+
5+
/**
6+
* Isolates the lowest set bit of the given number.
7+
* For example, if n = 18 (binary: 10010), the result will be 2 (binary: 00010).
8+
*
9+
* @param n the number whose lowest set bit will be isolated
10+
* @return the isolated lowest set bit of n
11+
*/
12+
public static int isolateLowestSetBit(int n) {
13+
// Isolate the lowest set bit using n & -n
14+
return n & -n;
15+
}
16+
17+
}
18+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
public class LowestSetBitTest {
8+
@Test
9+
void testLowestSetBitWithPositiveNumber() {
10+
// Test with a general positive number
11+
assertEquals(2, LowestSetBit.isolateLowestSetBit(18)); // 18 in binary: 10010, lowest bit is 2
12+
}
13+
14+
@Test
15+
void testLowestSetBitWithZero() {
16+
// Test with zero (edge case, no set bits)
17+
assertEquals(0, LowestSetBit.isolateLowestSetBit(0)); // 0 has no set bits, result should be 0
18+
}
19+
20+
@Test
21+
void testLowestSetBitWithOne() {
22+
// Test with number 1 (lowest set bit is 1 itself)
23+
assertEquals(1, LowestSetBit.isolateLowestSetBit(1)); // 1 in binary: 0001, lowest bit is 1
24+
}
25+
26+
@Test
27+
void testLowestSetBitWithPowerOfTwo() {
28+
// Test with a power of two (only one set bit)
29+
assertEquals(16, LowestSetBit.isolateLowestSetBit(16)); // 16 in binary: 10000, lowest bit is 16
30+
}
31+
32+
@Test
33+
void testLowestSetBitWithAllBitsSet() {
34+
// Test with a number with multiple set bits (like 7)
35+
assertEquals(1, LowestSetBit.isolateLowestSetBit(7)); // 7 in binary: 111, lowest bit is 1
36+
}
37+
38+
@Test
39+
void testLowestSetBitWithNegativeNumber() {
40+
// Test with a negative number (-1 in two's complement has all bits set)
41+
assertEquals(1, LowestSetBit.isolateLowestSetBit(-1)); // -1 in two's complement is all 1s, lowest bit is 1
42+
}
43+
44+
@Test
45+
void testLowestSetBitWithLargeNumber() {
46+
// Test with a large number
47+
assertEquals(64, LowestSetBit.isolateLowestSetBit(448)); // 448 in binary: 111000000, lowest bit is 64
48+
}
49+
}

0 commit comments

Comments
 (0)