Reverse a number without converting it to String

In this article we are going to discuss a problem from arrays; this is one of the most commonly asked interview question of today.
 

Reverse a number without changing it to string and without using reverse().

e.g. if given number is 12345 than we have to reverse it to 54321.


Here is a straight forward solution for the problem, We can reverse the number using some mathematical calculations as shown in example below:

package com.tbNext.byexample;

public class TBReverseANumber {

	public static void main(String[] args) {
		int input = 8787956;
		System.out.println("Reversed Number");
		while (input > 0) {
			int rem = input % 10;
			System.out.print(rem);
			input = (input - rem) / 10;
		}

	}

}

Output

Reversed Number
6597878


That's it, we have seen how to reverse a number without converting it to a string or without using reverse(). In upcoming articles of Java Algorithms and interview series we will see more about Java and Related programming problems and solutions.

About The Author

Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.