write a java program to convert ( input by user) decimal number to binary.
Answers
Answer:
import java.util.Scanner;
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)
{
count++;
}
x = a + "" + x;
n = n / 2;
}
System.out.println("Binary number:"+x);
System.out.println("No. of 1s:"+count);
}
}
Explanation:
import java.util.*;
class Dec_to_bin
{
public static void main(string args[])
{
Scanner sc=new Scanner(System.in());
System.out.println("enter a number");
int n=sc.nextInt();
String s=""
while (n>0)
{
if(n%2==0)
s="0"+s;
else
s="1"+s;
n/=2;
}
System.out.println("the binary form is"+s);
}
}