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 email@example.com. 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.
- Stack | Set 3 (Reverse a string using stack)
- Reverse the Sentence using 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
- Reverse bytes of a Hexadecimal Number
- Write a program to reverse digits of a number
- Write an Efficient C Program to Reverse Bits of a Number
- Check if the product of digit sum and its reverse equals the number or not
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Stack Permutations (Check if an array is stack permutation of other)
- Count the number of pop operations on stack to get each element of the array
- Find maximum in stack in O(1) without using additional stack
- Sort a stack using a temporary stack