Reversing the output of numbers in Java

2019-07-29 05:38发布

问题:

I'm trying to do a number system calculator but only using the control or repetitive structures. Here's my sample:

int base = 0, given = 0, remainder = 0;
// input given here
System.out.print("The answer is: ");
if (base == 2){
    while(given != 0){
    remainder = given % base;
    given /= base;
    System.out.print("" + remainder);
    }
}

And the output goes like this:

Input: 32
The answer is: 000001

The question is, how would I reverse the output to 100000 since the binary of 32 is 100000 and not 000001? The condition is not to use anything except the three repetitive structures: for, while and do-while and using decisive structures: if, else-if and for.

回答1:

You can concatenate the digits into a String and print it after the loop:

String output = "";
if (base == 2){
    while(given != 0){
        remainder = given % base;
        given /= base;
        output = remainder + output;
    }
    System.out.println(output);
}