Home »
Java Programs »
Java Basic Programs
Java program to count the number of leading zeros in a binary number
Given/input a number, we have to count the number of leading zeros in a binary number.
Submitted by Nidhi, on March 11, 2022
Problem statement
In this program, we will read an integer number from the user. Then we will print its binary representation and count the leading 0s in binary representation.
Java program to count the number of leading zeros in a binary number
The source code to count the number of leading zeros in a binary number is given below. The given program is compiled and executed successfully.
// Java program to count the number of
// leading zeros in a binary number
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner SC = new Scanner(System.in);
int num = 0;
int cnt = 31;
System.out.printf("Enter Number: ");
num = SC.nextInt();
System.out.printf("Binary number: ");
while (cnt >= 0) {
if ((num & (1 << cnt)) != 0)
System.out.printf("1");
else
System.out.printf("0");
cnt--;
}
cnt = 0;
while ((num & (1 << 31)) == 0) {
num = (num << 1);
cnt++;
}
System.out.printf("\nNumber of leading zero's are: %d\n", cnt);
}
}
Output
Enter Number: 8
Binary number: 00000000000000000000000000001000
Number of leading zero's are: 28
Explanation
In the above program, we imported the java.util.Scanner package to read the variable's value from the user. And, created a public class Main. It contains a static method main().
The main() method is an entry point for the program. Here, we read an integer number from the user. Then we printed its binary representation and count the leading 0's in the binary number. After that, we printed the number of leading 0's.
Java Basic Programs »