Related Articles
Add two numbers represented by Stacks
• Last Updated : 10 Jun, 2021

Given two numbers N1 and N2 represented by two stacks, such that their most significant digits are present at the bottom of the stack, the task is to calculate and return the sum of the two numbers in the form of a stack.

Examples:

Input: N1={5, 8, 7, 4}, N2={2, 1, 3}
Output: {6, 0, 8, 7}
Explanation:
Step 1: Popped element from N1(= 4) +  Popped element from N2(= 3) = {7} and rem=0.
Step 2: Popped element from N1(= 7) +  Popped element from N2(= 1) = {7, 8} and rem=0.
Step 3: Popped element from N1(= 8) +  Popped element from N2(= 2) = {7, 8, 0} and rem=1.
Step 4: Popped element from N1(= 5) = {7, 8, 0, 6}
On reverse the stack, the desired arrangement {6,0,8,7} is obtained.
Input: N1={6,4,9,5,7}, N2={213}
Output:{6, 5, 0, 0, 5}

Approach: The problem can be solved using the concept of Add two numbers represented by linked lists. Follow the below steps to solve the problem.

1. Create a new stack, res to store the sum of the two stacks.
2. Initialize variables rem and sum to store the carry generated and the sum of top elements respectively.
3. Keep popping the top elements of both the stacks and push the sum % 10 to res and update rem as sum/10.
4. Repeat the above step until the stacks are empty. If rem is greater than 0, insert rem into the stack.
5. Reverse the res stack so that the most significant digit present at the bottom of the res stack.

Below is the implementation of the resultant approach:

## C++14

 // C++ program to implement// the above approach#include using namespace std; // Function to return the stack that// contains the sum of two numbersstack addStack(stack N1,                    stack N2){    stack res;    int sum = 0, rem = 0;     while (!N1.empty() and !N2.empty()) {             // Calculate the sum of the top      // elements of both the stacks        sum = (rem + N1.top() + N2.top());             // Push the sum into the stack        res.push(sum % 10);             // Store the carry        rem = sum / 10;             // Pop the top elements        N1.pop();        N2.pop();    }       // If N1 is not empty    while (!N1.empty()) {        sum = (rem + N1.top());        res.push(sum % 10);        rem = sum / 10;        N1.pop();    }    // If N2 is not empty    while (!N2.empty()) {        sum = (rem + N2.top());        res.push(sum % 10);        rem = sum / 10;        N2.pop();    }     // If carry remains    while (rem > 0) {        res.push(rem);        rem /= 10;    }     // Reverse the stack.so that    // most significant digit is    // at the bottom of the stack    while (!res.empty()) {        N1.push(res.top());        res.pop();    }    res = N1;    return res;} // Function to display the// resultamt stackvoid display(stack& res){    int N = res.size();    string s = "";    while (!res.empty()) {        s = to_string(res.top()) + s;        res.pop();    }       cout << s << endl;} // Driver Codeint main(){    stack N1;    N1.push(5);    N1.push(8);    N1.push(7);    N1.push(4);     stack N2;    N2.push(2);    N2.push(1);    N2.push(3);     stack res = addStack(N1, N2);     display(res);       return 0;}

## Python3

 # Python3 program to implement# the above approach # Function to return the stack that# contains the sum of two numbersdef addStack(N1, N2):     res = []    s = 0    rem = 0     while (len(N1) != 0 and len(N2) != 0):         # Calculate the sum of the top        # elements of both the stacks        s = (rem + N1[-1] + N2[-1])         # Push the sum into the stack        res.append(s % 10)         # Store the carry        rem = s // 10         # Pop the top elements        N1.pop(-1)        N2.pop(-1)     # If N1 is not empty    while(len(N1) != 0):        s = rem + N1[-1]        res.append(s % 10)        rem = s // 10        N1.pop(-1)     # If N2 is not empty    while(len(N2) != 0):        s = rem + N2[-1]        res.append(s % 10)        rem = s // 10        N2.pop(-1)     # If carry remains    while(rem > 0):        res.append(rem)        rem //= 10     # Reverse the stack.so that    # most significant digit is    # at the bottom of the stack    res = res[::-1]     return res # Function to display the# resultamt stackdef display(res):     s = ""    for i in res:        s += str(i)     print(s) # Driver CodeN1 = []N1.append(5)N1.append(8)N1.append(7)N1.append(4) N2 = []N2.append(2)N2.append(1)N2.append(3) # Function callres = addStack(N1, N2) display(res) # This code is contributed by Shivam Singh

## C#

 // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the stack that// contains the sum of two numbersstatic Stack PushStack(Stack N1,                            Stack N2){    Stack res = new Stack();    int sum = 0, rem = 0;         while (N1.Count != 0 && N2.Count != 0)    {         // Calculate the sum of the top        // elements of both the stacks        sum = (rem + N1.Peek() + N2.Peek());         // Push the sum into the stack        res.Push((int)sum % 10);         // Store the carry        rem = sum / 10;         // Pop the top elements        N1.Pop();        N2.Pop();    }     // If N1 is not empty    while (N1.Count != 0)    {        sum = (rem + N1.Peek());        res.Push(sum % 10);        rem = sum / 10;        N1.Pop();    }         // If N2 is not empty    while (N2.Count != 0)    {        sum = (rem + N2.Peek());        res.Push(sum % 10);        rem = sum / 10;        N2.Pop();    }     // If carry remains    while (rem > 0)    {        res.Push(rem);        rem /= 10;    }     // Reverse the stack.so that    // most significant digit is    // at the bottom of the stack    while (res.Count != 0)    {        N1.Push(res.Peek());        res.Pop();    }         res = N1;    return res;} // Function to display the// resultamt stackstatic void display(Stack res){    int N = res.Count;    String s = "";         while (res.Count != 0)    {        s = String.Join("", res.Peek()) + s;        res.Pop();    }     Console.Write(s + "\n");} // Driver Codepublic static void Main(String[] args){    Stack N1 = new Stack();    N1.Push(5);    N1.Push(8);    N1.Push(7);    N1.Push(4);         Stack N2 = new Stack();    N2.Push(2);    N2.Push(1);    N2.Push(3);         Stack res = PushStack(N1, N2);         display(res);}} // This code is contributed by Amit Katiyar

## Javascript


Output:
6087

Time Complexity: O(N)
Auxiliary Space: O(N)

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up