2

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;
    }
  }
}

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.