This is a Java Program to Convert a Decimal Number to Binary & Count the Number of 1s.
Enter any integer as an input. Now we convert the given decimal input into a binary number with the help of division and modulus operations along with loops and if conditions to get the desired output.
Here is the source code of the Java Program to Convert a Decimal Number to Binary & Count the Number of 1s. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Convert
public static void main(String args)
int n, count = 0, a;
String x = “”;
Scanner s = new Scanner(System.in);
System.out.print(“Enter any decimal number:”);
n = s.nextInt();
while(n > 0)
a = n % 2;
if(a == 1)
x = a + “” + x;
n = n / 2;
System.out.println(“No. of 1s:”+count);
$ javac Convert.java
$ java Convert
Enter any decimal number:25
No. of 1s:3