This is the Java Program to Reverse a Given Number Without Using Recursion.
Write a Java Program to Reverse a Given Number Without Using Recursion.
Using a loop, extract the last digit of the number and add it at the end of the reverse formed till now.
.
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.
//Java Program to Reverse a Given Number Without Using Recursion
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ReverseNumber {
// Function to reverse the number without using recursion
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
try {
System.out.println("Enter a number");
n = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error occurred");
return;
}
int rev,i,s;
rev = 0;
for(i=n; i!=0; i/=10){
rev= rev*10+(i%10);
}
System.out.println("The reverse is " + rev);
}
}
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.
Time Complexity: O(1).
Case 1 (Simple Test Case): Enter a number 214224 The reverse is 422412
Sanfoundry Global Education & Learning Series – Java Programs..
- Practice BCA MCQs
- Practice Information Technology MCQs
- Check Programming Books
- Check Java Books
- Apply for Java Internship