Advertisement
ipilot

Lab_3_C++

Nov 17th, 2012
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <string>
  5. #define sz(a) (int)a.size()
  6. #define eq(a) for(int i=sz(a);i<k;i++)a.push_back(buf)
  7.  
  8. using namespace std;
  9.  
  10. const int nmax=4, D[5]={0,1,1,0,0}, E[5]={1,0,0,0,0}, Z[5]={0,0,0,0,0};
  11.  
  12. struct num {
  13.     int c[5];
  14.     void init(const int x[5] = Z) {
  15.         for (int i=0; i<=4; i++) this->c[i]=x[i]; }
  16.     void inc(const int x[5] = E)
  17.     {
  18.         for (int i = 0; i <= 4; i++)
  19.         {
  20.             this->c[i] += x[i];
  21.             if (this->c[i] > 1)
  22.                 this->c[i+1]+=this->c[i]/2, this->c[i]%=2;
  23.         }
  24.     }
  25. };
  26.  
  27. typedef vector < num > vn;
  28.  
  29. vn tonum(int x)
  30. {
  31.     int t, c; vn ans; num p;
  32.     while (x > 0)
  33.     {
  34.         p.init();
  35.         t = x % 10, x = x / 10, c = 0;
  36.         while (c < 5)   p.c[c++] = t % 2, t = t / 2;
  37.         ans.push_back(p);
  38.     }
  39.     return ans;
  40. }
  41.  
  42. vn sum(vn a, vn b)
  43. {
  44.     int k = max(sz(a), sz(b));
  45.     vn ans, temp;
  46.     num buf, over, o;
  47.     buf.init();
  48.     over.init(E);
  49.     bool of = false;
  50.     if (sz(a) > sz(b)) eq(b); else eq(a);
  51.     for (int i = 0; i < k; i++)
  52.     {
  53.         buf.init();
  54.         if (!of) ans.push_back(buf);
  55.         of = false;
  56.         buf.init(a[i].c);
  57.         buf.inc(b[i].c);
  58.         o.init(D);
  59.         o.inc(buf.c);
  60.         o.inc(ans[i].c);
  61.         if (o.c[4] > 0)
  62.         {
  63.             of = true;
  64.             o.c[4] = 0;
  65.             ans.back().init(o.c);
  66.             ans.push_back(over);
  67.         } else ans.back().inc(buf.c);
  68.     }
  69.     return ans;
  70. }
  71.  
  72. void printnum(vn x, string t = "")
  73. {
  74.     int c;
  75.     if (sz(x) > nmax) cout << "OVERFLOW\n", c = nmax; else c = sz(x);
  76.     for (int j = c-1; j >=0; j--)
  77.     {
  78.         for (int i = 3; i >= 0; i--) cout << x[j].c[i];
  79.         cout << " ";
  80.     }
  81.     if (t == "") t = "\n"; else t = "\n"+t+"\n";
  82.     cout << t;
  83. }
  84.  
  85. int main()
  86. {
  87.     //freopen("input.txt", "r", stdin);
  88.     int a, b;
  89.     vn A, B, C;
  90.     cin >> a >> b;
  91.     A = tonum(a);
  92.     printnum(A, "+");
  93.     B = tonum(b);
  94.     printnum(B, "=");
  95.     C = sum(A, B);
  96.     printnum(C);
  97.     return 0;
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement