×

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 file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 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 remove last character from String in Java

In java, there are predominantly three classes connected with the string. The classes are String, StringBuilder, and StringBuffer class that gives techniques connected with string control. Eliminating the first and...

5 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 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.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.