System.out.print("Enter an integer: ");
int number = input.nextInt();
String binary = "";
while(number != 0) {
if (number % 2 == 0) {
binary += "0" ;
} else{
binary += "1" ;
}
number /= 2;
}
System.out.println(binary);
I have trouble understanding what is wrong with my code.
I saw there are solutions to this question but they didn't answer the following question that I have :
I know that to display the binary the right way I need to change these line: binary += "0"; to this line: binary = "0" + binary;
I just can't understand WHY, why when I wrote that code the output is not reversed as it should be but If I add the lines it prints the right way.
Thanks.