Java Program to Reverse a Number without using Recursion

This is the Java Program to Reverse a Given Number Without Using Recursion.

Problem Description

Write a Java Program to Reverse a Given Number Without Using Recursion.

Problem Solution


Using a loop, extract the last digit of the number and add it at the end of the reverse formed till now.
.

Program/Source Code

Here is the source code of the Java Program to Reverse a Given Number Without Using Recursion. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

  1.  
  2. //Java Program to Reverse a Given Number Without Using Recursion
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.InputStreamReader;
  6.  
  7. public class ReverseNumber {
  8.     // Function to reverse the number without using recursion
  9.     public static void main(String[] args) {
  10.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  11.         int n;
  12.         try {
  13.             System.out.println("Enter a number");
  14.             n = Integer.parseInt(br.readLine());
  15.         } catch (Exception e) {
  16.             System.out.println("An error occurred");
  17.             return;
  18.         }
  19.         int rev,i,s;
  20.         rev = 0;
  21.         for(i=n; i!=0; i/=10){
  22.             rev= rev*10+(i%10);
  23.         }
  24.         System.out.println("The reverse is " + rev);
  25.     }
  26. }
Program Explanation

1. In function main(), firstly the number is taken as input.
2. Then, the loop for(i=n; i!=0; i/=10), runs until the each digit is extracted, in the reverse order.
3. The statement rev= rev*10+(i%10); adds the digit obtained to the reverse.

advertisement

Time Complexity: O(1).

Runtime Test Cases
 
Case 1 (Simple Test Case):
 
Enter a number
214224
The reverse is 422412

Sanfoundry Global Education & Learning Series – Java Programs..

🎓 Register Today for Free C++ Certification - December 2025

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.