想当年初学C++的时候写个大整数加法都快屎了,现在觉得自己还是成长了不少哇。
代码:
1 string multiply(string num1, string num2) { 2 int len1 = num1.length(); 3 int len2 = num2.length(); 4 vector<int> buffer(len1 + len2, 0); 5 6 for (int i = len1 - 1; i >= 0; i--) 7 for (int j = len2 - 1; j >= 0; j--) 8 buffer[len1 - 1 - i + len2 - 1 - j] += (num1[i] - '0') * (num2[j] - '0'); 9 10 for (int i = 0, carry = 0; i < len1 + len2; i++) { 11 buffer[i] += carry; 12 carry = buffer[i] / 10; 13 buffer[i] %= 10; 14 } 15 16 string res; 17 int p = len1 + len2 - 1; 18 while (p >= 0 && buffer[p] == 0) p--; 19 while (p >= 0) { 20 res += buffer[p] + '0'; 21 p--; 22 } 23 24 return res.empty() ? "0" : res; 25 }