简体   繁体   中英

Decimal to Binary program w/o built in method

I am making a decimal to binary program in an entry level AP computer science class. I used the decimal to binary algorithm but the program prints out the reverse of the binary string.

public static void main (String[]args) {

  int n = Integer.parseInt(args[0]);

  while (n>0) {   
    if (n%2==0) {   //for even numbers
      System.out.print("0");
      n/=2; //
    }
    else {
      System.out.print("1");
      n--; // for odd numbers
      n/=2;
    }
  }
}

If you understand that it's printing it out backwards, then perhaps you can make a simple fix.

Add a String variable and tack on the "1" or "0" in front of that variable, and the result at the end will be your binary result.

Sample code that will work is:

String ans = "";
...
ans = "1" + ans;

OR

ans = "0" + ans;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM