-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryadd.cpp
More file actions
100 lines (86 loc) · 1.7 KB
/
Copy pathbinaryadd.cpp
File metadata and controls
100 lines (86 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//Write C++ program using STL to add binary numbers (assume one bit as one number), use STL stack.
#include<iostream>
#include<stack>
using namespace std;
/* READ BINARY NUMBER */
stack<int> read()
{
stack<int> s;
int x,n,i;
cout<<"\nEnter the no. of bits in the no. :";
cin>>n;
cout<<"\nEnter the binary number : ";
for(i=0;i<n;i++)
{
cin>>x;
s.push(x);
}
return s;
}
/* DISPLAY FUNCTION */
void display(stack<int> &s)
{
cout<<" ";
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
}
/* ADDITION OF TWO BINARY NOS.*/
stack<int> add(stack<int> &s1,stack<int> &s2)
{
stack<int> s;
int sum,carry=0,b1,b2;
while(!s1.empty()||!s2.empty())
{
b1=b2=0;
if(!s1.empty())
{
b1=s1.top();
s1.pop();
}
if(!s2.empty())
{
b2=s2.top();
s2.pop();
}
sum=(b1+b2+carry)%2;
carry=(b1+b2+carry)/2;
s.push(sum);
}
if(carry==1)
s.push(1);
return s;
}
/* MAIN FUNCTION*/
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:
s1=read();
break;
case 2:
s2=read();
break;
case 3:
cout<<"\nThe result of addition is :";
s3=add(s1,s2);
display(s3);
break;
}
}while(ch!=4);
return 0;
}