Converting decimal to binary in java having troubl

2019-08-29 10:24发布

问题:

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+" ");
     }    
}
}

回答1:

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:

        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="";
        String reverse = "";
        while(x!=0){
           y=x%2;
           x=x/2;
           y1 = Integer.toString(y);
         //  System.out.print(y1+" ");
           reverse = y1+" "+reverse;
         }          
        System.out.println("Reverse Order :"+reverse);


回答2:

You can store the digits in some container(e.g. ArrayList) and then iterate it back to front printing each digit as you iterate.



回答3:

For adding to Ivaylo answer, you can also store it in a StringBuilder and reverse it using reverse method.