Skip to content

Commit 8949aa1

Browse files
committed
feat: Add countLeadingZeros new algorithm with Junit tests
1 parent 90d20b3 commit 8949aa1

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
public class CountLeadingZeros {
4+
5+
/**
6+
* Counts the number of leading zeros in the binary representation of a number.
7+
* Method: Keep shifting the mask to the right until the leftmost bit is 1.
8+
* The number of shifts is the number of leading zeros.
9+
*
10+
* @param num The input number.
11+
* @return The number of leading zeros.
12+
*/
13+
public static int countLeadingZeros(int num) {
14+
if (num == 0) {
15+
return 32;
16+
}
17+
18+
int count = 0;
19+
int mask = 1 << 31;
20+
while ((mask & num) == 0) {
21+
count++;
22+
mask >>>= 1;
23+
}
24+
25+
return count;
26+
}
27+
}
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 CountLeadingZerosTest {
8+
9+
@Test
10+
public void testCountLeadingZeros() {
11+
assertEquals(29, CountLeadingZeros.countLeadingZeros(5)); // 000...0101 has 29 leading zeros
12+
assertEquals(32, CountLeadingZeros.countLeadingZeros(0)); // 000...0000 has 32 leading zeros
13+
assertEquals(31, CountLeadingZeros.countLeadingZeros(1)); // 000...0001 has 31 leading zeros
14+
assertEquals(0, CountLeadingZeros.countLeadingZeros(-1)); // No leading zeros in negative number (-1)
15+
}
16+
}

0 commit comments

Comments
 (0)