public class RevereseNum { public static void main(String[] args) { int n, reverse = 0; System.out.println("Enter an integer to reverse"); Scanner in = new Scanner(System.in); n = in.nextInt(); while (n != 0) { reverse = reverse * 10; reverse = reverse + n % 10; n = n / 10; } System.out.println("Reverse of the number is " + reverse); 

This code requests the input of a number in the console, and then turns the numbers in reverse order, but I do not understand how this happens? Those. How does the number flip through this loop? Isn't the loop endless in this case?

  • one
    Debut tried? :) - Alex Sherzhukov
  • one
    Take a piece of paper, a pencil and some not very long number. Execute the cycle code on paper, report the results. - Igor

1 answer 1

Take the number on the input n=12345 and number the lines in the loop:

 while (n != 0) { //1 reverse = reverse * 10; //2 reverse = reverse + n % 10; //3 n = n / 10; } 

So, on the first iteration:

 reverse = 0 * 10; reverse = 0 + 12345 % 10; // = 0+5=5 n = 12345 / 10; // = 1234,5, но поскольку n - integer, приводится к 1234 //reverse = 5; n = 1234; 

Further:

 reverse = 5 * 10; // = 50 reverse = 50 + 1234 % 10; // = 50+4 = 54 n = 1234 / 10; // = 123 // reverse = 54; n = 123; 

Total: at each iteration, the code shifts the digits in the reverse one digit to the left, adds the least significant digit of n to the low-order bit, and shifts the digits in n to the right, removing the low-order bit.

  • Weakly chewed, chew more. - Igor
  • @Igor but where else, they will soon forget how to think :) - Alex Sherzhukov