×

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and so on until the middle element.

Note: After reversing, leading zeros would not be taken into account (i.e., 100 would become 001~ 1).

The procedures below must be taken in order to reverse a number:

  • Add 10 to the number's modulo.
  • The reverse number should be multiplied by 10 and the modulo value added.
  • Multiply the result by 10.
  • Till the number equals zero, repeat the previous steps.

Example

Before reversing => after reversing

5678                     =>    8765

Consider the case where we want to reverse the 5678

In this illustration, we've used three variables with initial values of 0: number (the value to be reversed), the remainder (which holds the remainder), and reverse (which stores the reverse number).

1st Iteration:

number =>  5678

remainder =>  5678 % 10 = 8

reverse => 0 * 10 + 8 = 0 + 8 = 8

number =>5678/ 10 =  567

The number as well as reverse variables now have values of 567 & 8, respectively.

 2nd Iteration:

number => 567

remainder => 567 % 10 = 7

reverse => 8 * 10 + 7 =  80 + 7 = 87

number => 567 / 10 = 56

The number, as well as reverse variables,as well as reverse variables now have values of 56 and 87, respectively.

3rd iteration:

number = > 56

remainder =>  56 % 10 = 6

reverse =>  87 * 10 + 6 = 870 + 6 = 876

number => 56/ 10 = 5

The number, as well as reverse variables, now have values of 5 & 876, respectively.

4th Iteration:

number = > 5

remainder =>  5 % 10 = 5

reverse =>  876 * 10 + 5 = 8760 + 5 = 8755

number = >5 / 10 = 0

The number, as well as reverse variables, now have values of 0& 8765, respectively.

By Using the While Loop

  • Simply implement the steps/algorithm discussed, and when the number reaches zero, end the loop.
  • Add 10 to the number's modulo.
  • The reverse number should be multiplied by 10 and the modulo value added.
  • Multiply the result by 10.
  • Up until the number reaches zero, repeat the previous steps.

Program 1

import java.io.*;
class Demo {
	static int reverse(int n){
	int rev = 0; 
	int rem; 
	while(n>0){
rem = n%10;
		rev = (rev*10) + rem;
		n = n/10;
	}
	return rev;
	}
	public static void main (String[] args) {
		int n = 4568;
		System.out.print("The Reversed Number is "+ reverse(n));
	}
}

Output

The Reversed Number is 8654

Program 2

public class Reverse
{  
public static void main(String[] args)   
{  
int number = 4579534, reverse = 0;  
while(number != 0)   
{  
int remainder = number % 10;  
reverse = reverse * 10 + remainder;  
number = number/10;  
}  
System.out.println("The reversed number is: " + reverse);  
}  
}  


Output

The reversed number is: 4359754

Complexities:

  • O(logn) is the time complexity, where n is a number.
  • Space complexity: O (logn)

By Using Recursion

The ultimate reverse number will be saved in the global variable "rev" during recursion. Please follow the guidelines below.

  • The base condition will be to stop the recursion if the number reaches zero.
  • Add modulo using the "rev*10" multiplication.
  • The number is multiplied by 10, and after being updated to number/10, the reverse procedure is called.

Program 1

import java.io.*;
class Demo {
	static int rev = 0;
	static void reverse(int n) {
	if(n<=0)
		return ;
	int rem = n%10; 
	rev = (rev*10) + rem;
	reverse(n/10);
	}
	public static void main (String[] args) {
		int n = 8760;
		reverse(n);
		System.out.print("The Reversed Number is "+ rev);
	}
}

Output

The reversed number is: 0678

Program 2

import java.util.Scanner;  
public class Reverse
{  
public static void reverseNumber(int n)   
{  
if (n < 20)   
{  
System.out.println(n);  
return;  
}  
else   
{  
System.out.print(n % 10);  
reverseNumber(n /10);  
}  
}  
public static void main(String args[])  
{  
System.out.print("Enter the number : ");  
Scanner sc = new Scanner(System.in);  
int num = sc.nextInt();  
System.out.print("The reversed number is: ");  
reverseNumber(num);  
}  
}    

Output

Enter the number: 2315
The reversed number is: 5132

Complexities

  • O(logn) is the time complexity, where n is a number.
  • Space complexity: O (logn)

By Using for loop

Program 1:

public class Reverse 
{  
public static void main(String[] args)   
{  
int number = 7876, reverse = 0;  
for( ;number != 0; number=number/10)   
{  
int remainder = number % 10;  
reverse = reverse * 10 + remainder;  
}  
System.out.println("The reversed number is: " + reverse);  
}  
}  

Output

The reversed number is: 6787

Program 2:

class Main {
  public static void main(String[] args) 
{
    int num = 6454, reversed = 0;
for(;num != 0; num /= 10) {
      int digit = num % 10;
      reversed = reversed * 10 + digit;
    }
System.out.println("The Reversed Number: " + reversed);
  }
}


Output

The reversed number is: 4546

Related Topics

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java. foreach loop in Java Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended...

4 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.