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** ;

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class reversenumber { public static void main(String args[]) { int num, rev=; Scanner sc=new Scanner(System.in); num=sc.nextInt(); while(num!=) { // 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); } } |

OUTPUT:

Incoming terms: program for revering a number.