Converting decimal to binary in java having trouble with reversing order

烈酒焚心 提交于 2019-12-12 01:04:08

问题


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.



来源:https://stackoverflow.com/questions/22008606/converting-decimal-to-binary-in-java-having-trouble-with-reversing-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!