fork download
  1. // C++ program to multiply two numbers
  2. // represented as strings.
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // Multiplies str1 and str2, and prints result.
  7. string multiply(string num1, string num2)
  8. {
  9. int n1 = num1.size();
  10. int n2 = num2.size();
  11. if (n1 == 0 || n2 == 0)
  12. return "0";
  13.  
  14. // will keep the result number in vector
  15. // in reverse order
  16. vector<int> result(n1 + n2, 0);
  17.  
  18. // Below two indexes are used to find positions
  19. // in result.
  20. int i_n1 = 0;
  21. int i_n2 = 0;
  22.  
  23. // Go from right to left in num1
  24. for (int i = n1 - 1; i >= 0; i--) {
  25. int carry = 0;
  26. int n1 = num1[i] - '0';
  27.  
  28. // To shift position to left after every
  29. // multiplication of a digit in num2
  30. i_n2 = 0;
  31.  
  32. // Go from right to left in num2
  33. for (int j = n2 - 1; j >= 0; j--) {
  34. // Take current digit of second number
  35. int n2 = num2[j] - '0';
  36.  
  37. // Multiply with current digit of first number
  38. // and add result to previously stored result
  39. // at current position.
  40. int sum = n1 * n2 + result[i_n1 + i_n2] + carry;
  41.  
  42. // Carry for next iteration
  43. carry = sum / 10;
  44.  
  45. // Store result
  46. result[i_n1 + i_n2] = sum % 10;
  47.  
  48. i_n2++;
  49. }
  50.  
  51. // store carry in next cell
  52. if (carry > 0)
  53. result[i_n1 + i_n2] += carry;
  54.  
  55. // To shift position to left after every
  56. // multiplication of a digit in num1.
  57. i_n1++;
  58. }
  59.  
  60. // ignore '0's from the right
  61. int i = result.size() - 1;
  62. while (i >= 0 && result[i] == 0)
  63. i--;
  64.  
  65. // If all were '0's - means either both or
  66. // one of num1 or num2 were '0'
  67. if (i == -1)
  68. return "0";
  69.  
  70. // generate the result string
  71. string s = "";
  72. while (i >= 0)
  73. s += std::to_string(result[i--]);
  74.  
  75. return s;
  76. }
  77.  
  78. // Driver code
  79. int main()
  80. {
  81. string str1 = "454545454545454545";
  82.  
  83. cout << multiply(str1, str1);
  84.  
  85. return 0;
  86. }
  87.  
Success #stdin #stdout 0s 4268KB
stdin
Standard input is empty
stdout
206611570247933883884297520661157025