Given a number , write a program to reverse this number using stack.
Input : 365 Output : 563 Input : 6899 Output : 9986
We have already discussed the simple method to reverse a number in this post. In this post we will discuss about how to reverse a number using stack.
The idea to do this is to extract digits of the number and push the digits on to a stack. Once all of the digits of the number are pushed to the stack, we will start poping the contents of stack one by one and form a number.
As stack is a LIFO data structure, digits of the newly formed number will be in reverse order.
Below is the implementation of above idea:
Time Complexity: O( logN )
Auxiliary Space: O( logN ), Where N is the input number.
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Stack | Set 3 (Reverse a string using stack)
- Sort a stack using a temporary stack
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Find maximum in stack in O(1) without using additional stack
- Reverse a stack using recursion
- Reverse a stack without using extra space in O(n)
- Program to reverse a linked list using Stack
- Print Reverse a linked list using Stack
- Java Program to Reverse a String using Stack
- Reverse the Words of a String using Stack
- Stack Permutations (Check if an array is stack permutation of other)
- C Program to reverse the digits of a number using recursion
- Implement Stack using Queues
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Implement a stack using single queue
- How to implement stack using priority queue or heap?
- Implement Stack and Queue using Deque
- Stack and Queue in Python using queue Module
- Check if a queue can be sorted into another queue using a stack
- Check for balanced parenthesis without using stack