Reversing the output of numbers in Java

大兔子大兔子 提交于 2019-12-11 05:22: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);
}


来源:https://stackoverflow.com/questions/46387309/reversing-the-output-of-numbers-in-java

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