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.
- Create a new stack, res to store the sum of the two stacks.
- Initialize variables rem and sum to store the carry generated and the sum of top elements respectively.
- Keep popping the top elements of both the stacks and push the sum % 10 to res and update rem as sum/10.
- Repeat the above step until the stacks are empty. If rem is greater than 0, insert rem into the stack.
- 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 <bits/stdc++.h>using namespace std;// Function to return the stack that// contains the sum of two numbersstack<int> addStack(stack<int> N1, stack<int> N2){ stack<int> 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<int>& 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<int> N1; N1.push(5); N1.push(8); N1.push(7); N1.push(4); stack<int> N2; N2.push(2); N2.push(1); N2.push(3); stack<int> res = addStack(N1, N2); display(res); return 0;} |
Java
// Java program to implement// the above approachimport java.util.Stack;class GFG{ // Function to return the stack that // contains the sum of two numbers static Stack<Integer> addStack(Stack<Integer> N1, Stack<Integer> N2) { Stack<Integer> res = new Stack<Integer>(); int sum = 0, rem = 0; while (!N1.isEmpty() && !N2.isEmpty()) { // Calculate the sum of the top // elements of both the stacks sum = (rem + N1.peek() + N2.peek()); // Push the sum into the stack res.add(sum % 10); // Store the carry rem = sum / 10; // Pop the top elements N1.pop(); N2.pop(); } // If N1 is not empty while (!N1.isEmpty()) { sum = (rem + N1.peek()); res.add(sum % 10); rem = sum / 10; N1.pop(); } // If N2 is not empty while (!N2.isEmpty()) { sum = (rem + N2.peek()); res.add(sum % 10); rem = sum / 10; N2.pop(); } // If carry remains while (rem > 0) { res.add(rem); rem /= 10; } // Reverse the stack.so that // most significant digit is // at the bottom of the stack while (!res.isEmpty()) { N1.add(res.peek()); res.pop(); } res = N1; return res; } // Function to display the // resultamt stack static void display(Stack<Integer> res) { int N = res.size(); String s = ""; while (!res.isEmpty()) { s = String.valueOf(res.peek()) + s; res.pop(); } System.out.print(s + "\n"); } // Driver Code public static void main(String[] args) { Stack<Integer> N1 = new Stack<Integer>(); N1.add(5); N1.add(8); N1.add(7); N1.add(4); Stack<Integer> N2 = new Stack<Integer>(); N2.add(2); N2.add(1); N2.add(3); Stack<Integer> res = addStack(N1, N2); display(res); }}// This code is contributed by shikhasingrajput |
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<int> PushStack(Stack<int> N1, Stack<int> N2){ Stack<int> res = new Stack<int>(); 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<int> 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<int> N1 = new Stack<int>(); N1.Push(5); N1.Push(8); N1.Push(7); N1.Push(4); Stack<int> N2 = new Stack<int>(); N2.Push(2); N2.Push(1); N2.Push(3); Stack<int> res = PushStack(N1, N2); display(res);}}// This code is contributed by Amit Katiyar |
Javascript
<script>// JavaScript program to implement// the above approach// Function to return the stack that// contains the sum of two numbersfunction addStack(N1, N2){ var res = []; var sum = 0, rem = 0; while (N1.length!=0 && N2.length!=0) { // Calculate the sum of the top // elements of both the stacks sum = (rem + N1[N1.length-1] +N2[N2.length-1]); // Push the sum into the stack res.push(sum % 10); // Store the carry rem = parseInt(sum / 10); // Pop the top elements N1.pop(); N2.pop(); } // If N1 is not empty while (N1.length!=0) { sum = (rem + N1[N1.length-1]); res.push(sum % 10); rem = parseInt(sum / 10); N1.pop(); } // If N2 is not empty while (N2.length!=0) { sum = (rem +N2[N2.length-1]); res.push(sum % 10); rem = parseInt(sum / 10); N2.pop(); } // If carry remains while (rem > 0) { res.push(rem); rem = parseInt(rem/10); } // Reverse the stack.so that // most significant digit is // at the bottom of the stack while (res.length!=0) { N1.push(res[res.length-1]); res.pop(); } res = N1; return res;}// Function to display the// resultamt stackfunction display(res){ var N = res.length; var s = ""; while (res.length!=0) { s = (res[res.length-1].toString()) + s; res.pop(); } document.write( s );}// Driver Codevar N1 = [];N1.push(5);N1.push(8);N1.push(7);N1.push(4);var N2 = [];N2.push(2);N2.push(1);N2.push(3);var res = addStack(N1, N2);display(res);</script> |
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


