File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed
main/java/com/thealgorithms/bitmanipulation
test/java/com/thealgorithms/bitmanipulation Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change 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+ }
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 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+ }
You can’t perform that action at this time.
0 commit comments