Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
Solution: Just like what we do when multiplying integers.
1 class Solution { 2 public: 3 string multiply(string num1, string num2) { 4 int N = num1.size(); 5 int M = num2.size(); 6 string res(N+M,'0'); 7 for(int i = N - 1; i >= 0; i--) { 8 int carry = 0; 9 for(int j = M - 1; j >= 0; j--) { 10 int sum = carry + (res[i+j+1] - '0') 11 + (num1[i] - '0')*(num2[j] - '0'); 12 res[i+j+1] = sum % 10 + '0'; 13 carry = sum / 10; 14 } 15 res[i] += carry; 16 } 17 while (res.size() > 1 && res[0] == '0') 18 res.erase(res.begin()); 19 return res; 20 } 21 };