Answer to Question #267661 in C++ for zxc

Question #267661

Algorithm addingLargeNumbers()

a create 3 empty stacks of integers (stack1, stack2, & result-stack)

b read numerals (digits) of first no & store nums corresponding to them on stack1

c read numerals (digits) of second no & store nums corresponding to them on stack2

d integer carry = 0

e while at least 1 stack is not empty

i pop a no from each nonempty stack & add them to carry

ii push unit part of sum on result-stack

iii store carry in carry

f push carry on result-stack if it is not zero

g pop numbers from result-stack & display them


Write C++ program for adding 2 very large nums 

1 Use Stack class to store integers

2 Program should read 2 numbers from console & store them as 2 strings

Suppose max no of numerals (digits) in a no is 30

3 After reading input determine sum of 2 large numbers by above algorithm & print on console


Input

123456789123456789123456789

123454321123454321123454321


Output

23456789123456789123456789

123454321123454321123454321

246911110246911110246911110




1
Expert's answer
2021-11-17T12:02:40-0500
#include<stack>
#include<iostream>
#include<string>
using namespace std;


int main(){
	stack<int>stack1;
	stack<int>stack2;
	stack<int>result_stack;
	string firstNumber = "123456789123456789123456789";
	
	
	for(int i=0; i<firstNumber.length(); i++){
		int n = firstNumber.at(i) - 48;
		stack1.push(n);
	}
	
	stack<int>temp;
	while(!stack1.empty()){
		
		temp.push(stack1.top());
		stack1.pop();
	}
	
	while(!temp.empty()){
		cout<<temp.top()<<" ";
		temp.pop();
	}


	
	string secondNumber = "123454321123454321123454321";


	
	for(int i=0; i<secondNumber.length(); i++){
		int n = secondNumber.at(i) - 48;
		stack2.push(n);
	}
	
	stack<int>temp2;
	while(!stack2.empty()){
		
		temp2.push(stack2.top());
		stack2.pop();
	}
	cout<<"\nThe content of stack 2 is:  \n";
	while(!temp2.empty()){
		cout<<temp2.top()<<" ";
		temp2.pop();
	}
	stack1  = temp;
	stack2  = temp2;
	while(!(stack1.empty()) || !(stack1.empty()) ){
		int n = stack1.top();
		int m = stack2.top();
		int res = m + n;
		
		result_stack.push(res);
		stack2.pop();
		stack1.pop();
	}
	
	stack<int>temp3;
	while(!stack2.empty()){
		
		temp3.push(result_stack.top());
		result_stack.pop();
	}
	cout<<"\nThe content of stack result_stack is:  \n";
	while(!temp3.empty()){
		cout<<temp3.top()<<" ";
		temp3.pop();
	}
	
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS