Skip to content
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
Uh oh!
There was an error while loading.
Please reload this page
.
TheAlgorithms
/
Java
Public
Notifications
You must be signed in to change notification settings
Fork
21.3k
Star
66.2k
Code
Issues
8
Pull requests
9
Actions
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Security and quality
Insights
Files
Expand file tree
master
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
thealgorithms
/
bitmanipulation
/
CountLeadingZeros.java
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
39 lines (35 loc) · 1.14 KB
master
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
thealgorithms
/
bitmanipulation
/
CountLeadingZeros.java
Copy path
Top
File metadata and controls
Code
Blame
39 lines (35 loc) · 1.14 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.thealgorithms.bitmanipulation;
/**
* CountLeadingZeros class contains a method to count the number of leading zeros in the binary representation of a number.
* The number of leading zeros is the number of zeros before the leftmost 1 bit.
* For example, the number 5 has 29 leading zeros in its 32-bit binary representation.
* The number 0 has 32 leading zeros.
* The number 1 has 31 leading zeros.
* The number -1 has no leading zeros.
*
* @author Hardvan
*/
public final class CountLeadingZeros {
private CountLeadingZeros() {
}
/**
* Counts the number of leading zeros in the binary representation of a number.
* Method: Keep shifting the mask to the right until the leftmost bit is 1.
* The number of shifts is the number of leading zeros.
*
* @param num The input number.
* @return The number of leading zeros.
*/
public static int countLeadingZeros(int num) {
if (num == 0) {
return 32;
}
int count = 0;
int mask = 1 << 31;
while ((mask & num) == 0) {
count++;
mask >>>= 1;
}
return count;
}
}
You can’t perform that action at this time.