/*============================================================================
Name : Exercise.cpp
Author : Haier
Version : 1.01
Copyright : Copyright (c) 2014
Description : binary addition in C++, Ansi-style, Compile by Eclipse
============================================================================*/
#include <iostream>
#include <stack>
#include <stdio.h>
using namespace std;
stack<int> read()
{
stack<int> MyStack;
int Number,Bit,i;
cout<<"Please input the Bit: ";
cin>>Number;
cout<<"Please input the Number of each Bit: ";
for(i=0; i<Number; i++)
{
cin>>Bit;
MyStack.push(Bit);
}
return MyStack;
}
void display(stack<int> &MyStack)
{
while(!MyStack.empty())
{
cout<<" "<<MyStack.top();
MyStack.pop();
}
}
stack<int> add(stack<int> &stack1,stack<int> &stack2)
{
int PlusNumber=0,Addend=0;
int Sum=0,Carry=0;
stack<int> Mystack;
while(!stack1.empty() || !stack2.empty())
{
if(!stack1.empty())
{
PlusNumber=stack1.top();
stack1.pop();
}
if(!stack2.empty())
{
Addend=stack2.top();
stack2.pop();
}
Sum =(PlusNumber+Addend+Carry)%2;
Carry=(PlusNumber+Addend+Carry)/2;
Mystack.push(Sum);
}
if(Carry==1)
{
Mystack.push(Carry);
}
return Mystack;
}
int main()
{
stack<int> s1,s2,s3;
int ch;
cout<<"\n\t\t\t***MENU***\n";
cout<<"\n1........Read first number"
<<"\n2........Read second number"
<<"\n3........Display addtion of two numbers"
<<"\n4........Exit";
do
{
cout<<"\nEnter your choice..: ";
cin>>ch;
switch(ch)
{
case 1:
fflush(stdin);
s1=read();
break;
case 2:
fflush(stdin);
s2=read();
break;
case 3:
cout<<"\nThe result of addition is :";
s3=add(s1,s2);
display(s3);
break;
}
}while(ch!=4);
return 0;
}