Java: Accept an integer and convert it into a binary representation
Binary Zeros Count
Write a Java program that will accept an integer and convert it into a binary representation. Now count the number of bits equal to zero in this representation.
Visual Presentation:
Sample Solution:
Java Code:
 import java.util.Scanner;
public class Solution {
    // Method to count the number of zero bits in the binary representation of a number
    public static int countBitsTozeroBasedOnString(int n) {
        int ctr = 0; // Initialize counter to count zero bits
        String binaryNumber = Integer.toBinaryString(n); // Convert integer 'n' to its binary representation
        System.out.print("Binary representation of " + n + " is: " + binaryNumber); // Display binary representation
        for (char ch : binaryNumber.toCharArray()) {
            ctr += ch == '0' ? 1 : 0; // Increment counter for each '0' bit encountered
        }
        return ctr; // Return count of zero bits
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in); // Create Scanner object to take user input
        System.out.print("Input first number: "); // Prompt user to input a number
        int n = in.nextInt(); // Read input number
        System.out.println("\nNumber of zero bits: " + countBitsTozeroBasedOnString(n)); // Display count of zero bits
    }
}
Sample Output:
Input first number: 25 Binary representation of 25 is: 11001 Number of zero bits: 2s
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to convert an integer to binary and count the number of one bits.
 - Write a Java program to represent an integer as an 8-bit binary string and count the zero bits.
 - Write a Java program to take a binary string input and determine the number of zero characters it contains.
 - Write a Java program to display the positions of all zeros in the binary representation of a given integer.
 
Go to:
PREV : Numbers Greater Than Average.
NEXT : Divide Using Subtraction.
Java Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
