From 050973a3b972469e95a58760beaccffb99af428f Mon Sep 17 00:00:00 2001 From: AnshuSahoo <72138869+AnshuSahoo@users.noreply.github.com> Date: Sun, 11 Oct 2020 03:05:00 +0530 Subject: [PATCH] Add_BInary_nos.cpp Simple Cpp program using Standard Template Library to add 2 binary digit numbers (assume one bit as one number) --- AddBinary_num.cpp | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 AddBinary_num.cpp diff --git a/AddBinary_num.cpp b/AddBinary_num.cpp new file mode 100644 index 000000000..6371dedce --- /dev/null +++ b/AddBinary_num.cpp @@ -0,0 +1,63 @@ +#include +#include +using namespace std; +stack read() +{ + char a[40]; + stack s; + cout<<"\n Enter a binary number: "; + cin>>a; + for(int i=0;a[i]!='\0';i++) + { + if(a[i]=='1') + s.push(1); + else + if(a[i]=='0') + s.push(0); + } + return s; +} +stack add(stack &s1,stack &s2) +{ + stack s; + int sum,carry=0,bit1,bit2; + while(!s1.empty()||!s2.empty()) + { + bit1=bit2=0; + if(!s1.empty()) + { + bit1=s1.top(); + s1.pop(); + } + if(!s2.empty()) + { + bit2=s2.top(); + s2.pop(); + } + sum=(bit1+bit2+carry)%2; + carry=(bit1+bit2+carry)/2; + s.push(sum); + } + if(carry==1) + s.push(1); + return s; +} +void display(stack &s) +{ + cout<<"\n Sum= "; + while(!s.empty()) + { + cout< s1,s2,s3; + + s1=read(); + s2=read(); + s3=add(s1,s2); + display(s3); + return 0; +}