jannatin nayem sourav
jannatin nayem sourav

Reputation: 25

How got the reverse number?

I m not understanding the meaning of using this lines

this are on the while block.

import java.util.Scanner;

public class ReverseNumberWhile {
    public static void main(String[] args){

       int num = 0;
       int reversenum = 0;

       System.out.println("Enter your number and press enter: ");

       Scanner input = new Scanner(System.in);
       num = input.nextInt();

       while(num != 0) {
           reversenum = reversenum * 10;
           reversenum = reversenum + num%10;
           num = num/10;
       }

       System.out.println("Reverse of input number is: " + reversenum);
   } 
}

Upvotes: 0

Views: 256

Answers (2)

Sergei Tachenov
Sergei Tachenov

Reputation: 24919

This code produces the number reversenum with the same digits as num, but in reversed order. For example, if num==12345, then reversenum==54321. It works by chopping the digits of num one-by-one, starting with the last one, and adding them to reversenum. The loop can be described as follows:

  1. Append the last digit of num to reversenum (the first two lines).
  2. Remove the last digit of num (the last line).

This repeats as long as there are any digits left in num, that is, while it's non-zero.

The first two lines can actually be written as a single line:

reversenum = reversenum * 10 + num % 10;

This way it actually makes more sense because you can see what's going on here: we take reversenum, shift its digits to the left (by multiplying by 10) and then add the last digit of num (which is obtained by num % 10).

Upvotes: 1

Naman
Naman

Reputation: 32036

There you go,commented :

 while(num != 0)
       {
           reversenum = reversenum * 10; //This moves the reversenum attained in previous iteration to one higher place value
           reversenum = reversenum + num%10; // num%10 gives you the last digit which is added to the existing reversenum
           num = num/10; //This leaves the remaining digits removing rightmost
       }

Upvotes: 2

Related Questions