Open In App

Reverse a number using stack

Last Updated : 15 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number , write a program to reverse this number using stack.

Examples: 

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 popping 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: 

C++





Java




// Java program to reverse the number
// using a stack
import java.util.Stack;
 
public class GFG
{
    // Stack to maintain order of digits
    static Stack<Integer> st= new Stack<>();
 
    // Function to push digits into stack
    static void push_digits(int number)
    {
        while(number != 0)
        {
            st.push(number % 10);
            number = number / 10;
        }
    }
 
    // Function to reverse the number
    static int reverse_number(int number)
    {
        // Function call to push number's
        // digits to stack
        push_digits(number);
        int reverse = 0;
        int i = 1;
 
        // Popping the digits and forming
        // the reversed number
        while (!st.isEmpty())
        {
            reverse = reverse + (st.peek() * i);
            st.pop();
            i = i * 10;
        }
 
        // Return the reversed number formed
        return reverse;
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
        int number = 39997;
        System.out.println(reverse_number(number));
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program to reverse the
# number using a stack
 
# Stack to maintain order of digits
st = [];
 
# Function to push digits into stack
def push_digits(number):
 
    while (number != 0):
        st.append(number % 10);
        number = int(number / 10);
 
# Function to reverse the number
def reverse_number(number):
     
    # Function call to push number's
    # digits to stack
    push_digits(number);
     
    reverse = 0;
    i = 1;
     
    # Popping the digits and forming
    # the reversed number
    while (len(st) > 0):
        reverse = reverse + (st[len(st) - 1] * i);
        st.pop();
        i = i * 10;
     
    # Return the reversed number formed
    return reverse;
 
# Driver Code
number = 39997;
 
# Function call to reverse number
print(reverse_number(number));
 
# This code is contributed by mits


C#





PHP




<?php
// PHP program to reverse the number
// using a stack
 
// Stack to maintain order of digits
$st = array();
 
// Function to push digits into stack
function push_digits($number)
{
    global $st;
    while ($number != 0)
    {
        array_push($st, $number % 10);
        $number = (int)($number / 10);
    }
}
 
// Function to reverse the number
function reverse_number($number)
{
    global $st;
     
    // Function call to push number's
    // digits to stack
    push_digits($number);
     
    $reverse = 0;
    $i = 1;
     
    // Popping the digits and forming
    // the reversed number
    while (!empty($st))
    {
        $reverse = $reverse +
                  ($st[count($st) - 1] * $i);
        array_pop($st);
        $i = $i * 10;
    }
     
    // Return the reversed number formed
    return $reverse;
}
 
// Driver Code
$number = 39997;
 
// Function call to reverse number
echo reverse_number($number);
 
// This code is contributed by mits
?>


Javascript




<script>
 // JavaScript program for the above approach
 
        // Stack to maintain order of digits
        let st = [];
 
        // Function to push digits into stack
        function push_digits(number)
        {
            while (number != 0)
            {
                st.push(number % 10);
                number = Math.floor(number / 10);
            }
        }
 
        // Function to reverse the number
        function reverse_number(number)
        {
         
            // Function call to push number's
            // digits to stack
            push_digits(number);
 
            let reverse = 0;
            let i = 1;
 
            // Popping the digits and forming
            // the reversed number
            while (st.length != 0) {
                reverse = reverse + (st[st.length - 1] * i);
                st.pop();
                i = i * 10;
            }
 
            // Return the reversed number formed
            return reverse;
        }
 
        // Driver program to test above function
        let number = 39997;
 
        // Function call to reverse number
        document.write(reverse_number(number));
 
// This code is contributed by Potta Lokesh
</script>


Output

79993

Time Complexity: O( logN ) 
Auxiliary Space: O( logN ), Where N is the input number.

 



Previous Article
Next Article

Similar Reads

Print Reverse a linked list using Stack
Given a linked list, print the reverse of it without modifying the list. Examples: Input : 1 2 3 4 5 6 Output : 6 5 4 3 2 1 Input : 12 23 34 45 56 67 78 Output : 78 67 56 45 34 23 12 Below are different solutions that are now allowed here as we cannot use extra space and modify the list. Recursive solution to print reverse a linked list. Requires e
9 min read
Program to reverse a linked list using Stack
Given a linked list. The task is to reverse the order of the elements of the Linked List using an auxiliary Stack. Examples: Input : List = 3 -&gt; 2 -&gt; 1 Output : 1 -&gt; 2 -&gt; 3 Input : 9 -&gt; 7 -&gt; 4 -&gt; 2 Output : 2 -&gt; 4 -&gt; 7 -&gt; 9 Algorithm: Traverse the list and push all of its nodes onto a stack.Traverse the list from the h
7 min read
Reverse alternate levels of a perfect binary tree using Stack
Given a Perfect Binary Tree, the task is to reverse the alternate level nodes of the binary tree.Examples: Input: a / \ b c / \ / \ d e f g / \ / \ / \ / \ h i j k l m n o Output: Inorder Traversal of given tree h d i b j e k a l f m c n g o Inorder Traversal of modified tree o d n c m e l a k f j b i g h Input: a / \ b c Output: Inorder Traversal
10 min read
Reverse the Words of a String using Stack
Given string str consisting of multiple words, the task is to reverse the entire string word by word.Examples: Input: str = "I Love To Code" Output: Code To Love IInput: str = "data structures and algorithms" Output: algorithms and structures data Approach: This problem can be solved not only with the help of the strtok() but also it can be solved
8 min read
Java Program to Reverse a String using Stack
The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first. Approach: Push the character one by one into the Stack of datatype character.Pop the character one by one from the Stack until the stack becomes empty.Add a popped element to the character
2 min read
Reverse an array using Stack
Given an array arr[] of size N, the task to reverse the array using Stack. Examples: Input: arr[] = { 10, 20, 30, 40, 50 } Output: 50 40 30 20 10 Explanation: Reversing the array modifies arr[] to { 50, 40, 30, 20, 10 } Therefore, the required output is 50 40 30 20 10. Input: arr[] = { 1 } Output: 1 Iterative and Recursive Approach: Refer the artic
12 min read
Reverse a Stack using Queue
Given a stack, the task is to reverse the stack using the queue data structure. Examples: Input: Stack: (Top to Bottom) [10 -&gt; 20 -&gt; 30 -&gt; 40]Output: Stack: (Top to Bottom) [40 -&gt; 30 -&gt; 20 -&gt; 10] Input: Stack: [6 -&gt; 5 -&gt; 4]Output: Stack: [4 -&gt; 5 -&gt; 6] Approach: The problem can be solved based on the following idea: The
5 min read
How to Reverse a String using Stack
Given a string, reverse it using stack. Example: Input: str = "GeeksQuiz"Output: ziuQskeeG Input: str = "abc"Output: cba Recommended PracticeReverse a string using StackTry It! Approach: The idea is to create an empty stack and push all the characters from the string into it. Then pop each character one by one from the stack and put them back into
12 min read
C Program to Reverse a Stack using Recursion
Write a program to reverse a stack using recursion, without using any loop. Example:  Input: elements present in stack from top to bottom 1 2 3 4 Output: 4 3 2 1  Input: elements present in stack from top to bottom 1 2 3Output: 3 2 1 Recommended PracticeReverse a StackTry It!Reverse a stack using Recursion The idea of the solution is to hold all va
5 min read
C++ Program to Reverse a String Using Stack
Given a string, reverse it using stack. For example "GeeksQuiz" should be converted to "ziuQskeeG". Following is simple algorithm to reverse a string using stack. 1) Create an empty stack.2) One by one push all characters of string to stack.3) One by one pop all characters from stack and put them back to string.Recommended PracticeReverse a string
4 min read
Practice Tags :