Advertisement
GastonFontenla

Solucion Gaston 2.0 C

Nov 11th, 2018
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #ifndef BIGNUMBER_H_INCLUDED
  2. #define BIGNUMBER_H_INCLUDED
  3.  
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <string.h>
  7.  
  8. using namespace std;
  9.  
  10. class BigNumber
  11. {
  12. private:
  13.     string n;
  14. public:
  15.     BigNumber(string _n); ///Constructor
  16.     string toStr(); ///Devolver string
  17.     BigNumber operator*(BigNumber &b); ///Operador multiplicar
  18. };
  19.  
  20. BigNumber::BigNumber(string _n)
  21. {
  22.     this->n = _n;
  23. }
  24.  
  25. string BigNumber::toStr()
  26. {
  27.     return this->n;
  28. }
  29.  
  30. BigNumber BigNumber::operator*(BigNumber &num)
  31. {
  32.     string sa = this->toStr();
  33.     string sb = num.toStr();
  34.     char *a = (char*)sa.c_str();
  35.     char *b = (char*)sb.c_str();
  36.     int t1 = sa.size(), t2 = sb.size();
  37.     int tam = t1+t2+1; ///+1 changui
  38.     int res[tam], p, i, j;
  39.  
  40.     for(i=0; i<tam; i++)
  41.         res[i] = 0;
  42.  
  43.     for(i=0; i<t1/2; i++)
  44.     {
  45.         swap(a[i], a[t1-1-i]);
  46.         swap(b[i], b[t2-1-i]);
  47.     }
  48.  
  49.     for(i=0; i<t1; i++)
  50.     {
  51.         for(j=0; j<t2; j++)
  52.         {
  53.             p = (a[i]-'0')*(b[j]-'0');
  54.             res[i+j] += p;
  55.         }
  56.     }
  57.  
  58.     for(i=0; i<tam-1; i++)
  59.     {
  60.         if(res[i] > 9)
  61.         {
  62.             res[i+1] += res[i]/10;
  63.             res[i] %= 10;
  64.         }
  65.     }
  66.  
  67.     int maxPos = tam-1;
  68.     while(maxPos >= 0 && res[maxPos] == 0)
  69.         maxPos--;
  70.  
  71.     char r[maxPos+2];
  72.     for(i=maxPos; i>=0; i--)
  73.         r[maxPos-i] = (res[i]+'0');
  74.     r[maxPos+1] = 0;
  75.  
  76.     return string(r);
  77. }
  78.  
  79. ostream &operator<<(ostream &out, BigNumber &num)
  80. {
  81.     return out << num.toStr();
  82. }
  83.  
  84. #endif // BIGNUMBER_H_INCLUDED
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement