Java program to convert decimal to binary and count number of 1s

Hey guys!! Welcome to flower brackets blog. Let’s learn java program to convert decimal to binary and count number of 1s.

Java program to convert decimal to binary and count number of 1s

First user enters an integer number as an input. Then for the conversion from decimal to binary, division and modulus operation is used with for loops to get output.

Also read – java decimal to binary using toBinaryString and stack

import java.util.Scanner;

public class DecimalBinaryDemo
{
public static void main(String[] args)
{
int number, count = 0, temp;
String strConvert = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter a decimal number : ");
number = sc.nextInt();
while(number > 0)
{
temp = number % 2;
if(temp == 1)
{
count++;
}
strConvert = strConvert + " " + temp;
number = number / 2;
}
System.out.println("Binary number : " + strConvert);
System.out.println("Number of 1s : " + count);
sc.close();
}
}

Output:

Enter a decimal number : 266
Binary number : 0 1 0 1 0 0 0 0 1
Number of 1s : 3

Also read – decimal to binary java logic

Related Posts