In: Computer Science
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:
As long as x is greater than 0 Output x % 2 (remainder is either 0 or 1)
x = x / 2
Note: The above algorithm outputs the 0's and 1's in reverse order.
The code needs to be in Java
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the positive integer");
int x=sc.nextInt();
String s = "";
while (x > 0)
{
if (x% 2 == 0)
s=s+"0";
else
s=s+"1";
x = x / 2;
}
System.out.println("The output is : "+s);
}
}