In this program, we are going to share reverse a number using stack with the output. If you are a Java beginner and want to start learning the Java programming, then keep your close attention in this tutorial as I am going to share how to write reverse a number using the stack.
Copy the below Java program and execute it with the help of Javac compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.Stack; public class ReverseNumberProgram { static Stack<Integer> st= new Stack<>(); static void push_digits(int number) { while(number != 0) { st.push(number % 10); number = number / 10; } } static int reverse_number(int number) { push_digits(number); int reverse = 0; int i = 1; while (!st.isEmpty()) { reverse = reverse + (st.peek() * i); st.pop(); i = i * 10; } return reverse; } public static void main(String[] args) { int number = 987654321; System.out.println(reverse_number(number)); } } |
123456789
Liked this program? Do Like & share with your friends 🙂
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: algorithm to reverse a string using stack, How to reverse a number using stack, java program to reverse a number using stack, reverse a number using stack in java, reverse stack using two stacks, String reversal using stack, Write a java program to reverse, Write a program to reverse a number in Java