Learn how to reverse a number in java language

In this article, you’ll learn how to reverse of a number in java language without giving input from the keyboard or giving input from the keyboard

In the above diagram, First, imagine the output screen

Enter a number:8614, if user write 4168 then our next step is to reverse the number that user enter and print on the screen in next line;

Reverse number: 4168

To reverse the number we create three variable x, r and initially y=0. We store the number enter by user users in x variable, and take one number from right-hand side ( i.e.,8 in this program) and store in variable r, then from r store the number in variable y.

For doing the above process we follow the following step:

  • x%10; it means 8614%10 gives remainder 4 and r=x%10; store the number 4 in variable r,
  • y=r then from r variable the number 4 is stored in variable y which is initially 0. So y=4;
  • x=x/10; it means 8614/10 then it gives the result i.e.,

again, repeat this process until x=0;

  • now the new value of x=861
  • x%10; it means 861%10 gives remainder 1 then store this number in variable r i.e.; r=x%10;
  • when 2nd time store the value of r in variable y, then multiply 10 by the previous value of y and add the value of r i.e.; y=10*y+r; put the value of y and r we get the new value of y. y=10*4+1; so new value of y=41
  • x/10; it gives a new value of x that is 86

Repeat the above process until x=0. Then we find the reverse number of x that is stored in variable y and print the variable y to get the result.

Example 1: write a program in java to print a reverse of a number in java without giving input from keyboard

import java.util.Scanner;

 

public class ReadData {

public static void main(String args[]) {

int x=8614, y=0,r;

while(x!=0) {

r=x%10;

y=y*10+r;

x=x/10;}

System.out.println(“Reverse Number= “+ y);

} }

 

The output of this program:

Reverse Number= 4168

 

Example 2: write a program in java to print a reverse of a number, the input is given by the user from the keyboard.

Solution:

import java.util.Scanner;

 

public class ReverseNumber {

public static void main(String args[]) {

int y=0,r;

System.out.print (“Enter two number: “);

Scanner sc=new Scanner(System.in);

int x=sc.nextInt();

while(x!=0) {

r=x%10;

y=y*10+r;

x=x/10;}

System.out.println(“Reverse Number= “+ y);

} }

 

The output of this program:

Enter two number: 8614

Reverse Number= 4168

 

Calculate L.C.M of two number in java language.

Leave a Reply

Your email address will not be published. Required fields are marked *