Tuesday 27 October 2015

Java program for reversing a number

This program reverses a number given as a input. This java program for reversing a number uses a concept of dividing the given number by 10 and adding the remainder to the units digit in  new number everytime. You can add to a unit place everytime by multiplying a number by 10 first(which will leave unit digit as 0) and then a number.

rev=(rev*10) + num%10;
let:  num=123; rev=0 (initially)
Iteration 1: num%10 = 3;
Therefore: rev= rev*10   + num%10  = 0*10 + 3 = 3 ;
Iteration 2: num=num/10 ; thus num=12;  Now, num%10 = 2;
Therefore:  rev= rev*10  +  num%10  = 3*10 + 2 = 32 ;
Iteration 3: num/=10; thus num=1; Now, num%10= 1;
Therefore:  rev= rev*10  +  num%10  = 32*10 + 1 = 321 ;

class reversenumber
{
public static void main(String args[])
{
int num, rev=0;
Scanner sc=new Scanner(System.in);
num=sc.nextInt();
while(num!=0)
{ //
rev=(rev*10)+num%10; // adding the remainder of a number(modulo 10) to the units place everytime.
num/=10; // Moving to the next digit. (removing the unit place of the given number everytime).
}
System.out.println("reverse of a number is: "+rev);
}
}

No comments:

Post a Comment