Advertisement
Eternoseeker

BInary addition oop

Dec 23rd, 2022
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | Source Code | 0 0
  1. #include<iostream>
  2. #include<stack>
  3. using namespace std;
  4.  
  5. stack <int>read(int bits){
  6.     stack <int>s;
  7.     for(int i = 0; i < bits; i++){
  8.         int n1;
  9.         cout << "Enter digit " << i+1 << ": " << endl;
  10.         cin >> n1;
  11.         s.push(n1);
  12.     }
  13.     return s;
  14. }
  15.  
  16. stack <int> add(stack <int>a1, stack <int>a2, int num){
  17.     stack <int>add;
  18.     int carry = 0;
  19.     int n1 = 0, n2= 0, sum = 0;
  20.     for(int i = 0; i < num; i++){
  21.         n1 = a1.top();
  22.         n2 = a2.top();
  23.         a1.pop();
  24.         a2.pop();
  25.         sum = (n1 + n2 + carry)%2;
  26.         add.push(sum);
  27.         carry = (n1 + n2 + carry)/2;
  28.     }
  29.     if(carry == 1){
  30.         add.push(carry);
  31.     }
  32.     return add;
  33. }
  34.  
  35. void display(stack <int> dis){
  36.     while(!dis.empty()){
  37.         int t = dis.top();
  38.         cout << t << " ";
  39.         dis.pop();
  40.     }
  41. }
  42.  
  43. int main(){
  44.     stack <int>s1, s2, s3;
  45.     int n = 0;
  46.     cout << "Enter no of bits" << endl;
  47.     cin >> n;
  48.     cout << "Enter stack 1 numbers: " << endl;
  49.     s1 = read(n);
  50.     cout << "Enter stack 2 numbers: " << endl;
  51.     s2 = read(n);
  52.     s3 = add(s1, s2, n);
  53.     display(s3);
  54.     return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement