Hey so I'm taking my first cs course ever at my university its taught in java. I'm having trouble converting decimal to binary. I seem to be able to get the correct output but its in reverse order, and I have no idea how to put it in the correct order, here is what I've coded so far,
import java.util.*;
public class lab6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number to convert to binary: ");
int x = input.nextInt();
int y;
String y1="";
while(x!=0){
y=x%2;
x=x/2;
y1 = Integer.toString(y);
System.out.print(y1+" ");
}
}
}
For adding to Ivaylo answer, you can also store it in a
StringBuilder
and reverse it using reverse method.You can store the digits in some container(e.g.
ArrayList
) and then iterate it back to front printing each digit as you iterate.It seems you are showing the output in correct order only. But if you want to reverse the current output you can use below code: