fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. class BigInteger
  7. {
  8. friend ostream& operator<<(ostream&, const BigInteger&);
  9.  
  10. public:
  11. BigInteger() = default;
  12. BigInteger(string);
  13. ~BigInteger() = default;
  14. BigInteger(const BigInteger&);
  15. BigInteger& operator=(const BigInteger&);
  16.  
  17. BigInteger& operator+(BigInteger&);
  18. BigInteger& operator-(BigInteger&);
  19. BigInteger& operator*(const BigInteger&);
  20.  
  21. private:
  22. string num;
  23. };
  24.  
  25. BigInteger& BigInteger::operator*(const BigInteger& rhs)
  26. {
  27. string tmp(num.length() + rhs.num.length(), '0');
  28. //a string in which I'll be temporarily storing the result
  29. unsigned char carry = '0';
  30. int d = 0;
  31. //I'll use this to move with one index to the left in the result
  32. for (int i = num.length() - 1; i >= 0; --i)
  33. //start with the multiplying from the end of the first number
  34. {
  35. carry = '0';
  36. for (int j = rhs.num.length() - 1, z = tmp.length() - 1 - d; j >= 0; --j, --z)
  37. //start with the multiplying from the end of the second number and begin filling the result string (again from the end)
  38. {
  39. int res = ((tmp[z] - '0') + (num[i] - '0') * (rhs.num[j] - '0') + (carry - '0'));
  40. carry = (res / 10) + '0';
  41. tmp[z] = (res % 10) + '0';
  42. if (j == 0)
  43. {
  44. tmp[z - 1] = carry;
  45. }
  46. }
  47. ++d;
  48. }
  49. if (carry != '0')
  50. {
  51. tmp[0] = carry;
  52. }
  53. else
  54. {
  55. tmp.erase(0, 1);
  56. }
  57. num = tmp;
  58. return *this;
  59. }
  60.  
  61. ostream& operator<<(ostream& out, const BigInteger& rhs)
  62. {
  63. out << rhs.num;
  64. return out;
  65. }
  66.  
  67. BigInteger::BigInteger(string num)
  68. :num(num)
  69. {}
  70.  
  71. int main()
  72. {
  73. BigInteger num3("6789");
  74. BigInteger num4("9876");
  75. cout << num3 <<"*" << num4 << endl;
  76. cout << num3 * num4 << endl;
  77. cout <<endl;
  78. cout << 6789 * 9876 << endl;
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0s 4360KB
stdin
Standard input is empty
stdout
6789*9876
67048164

67048164