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.
大数相乘,就是模拟乘法的过程,注意好下标,别忘了最后检查高位的0就好。看代码:
1 class Solution { 2 public: 3 string multiply(string num1, string num2) { 4 size_t size1 = num1.size(); 5 size_t size2 = num2.size(); 6 size_t total = size1 + size2; 7 vector<int> ret(size1 + size2, 0); 8 // 各位相乘 9 for (size_t i = 0; i < size1; ++i) { 10 for (size_t j = 0; j < size2; ++j) { 11 // 想明白为什么下标是i+j 12 ret[i + j] += (num1[size1 - i - 1] - '0') * (num2[size2 - j - 1] - '0'); 13 } 14 } 15 // 进位一起处理 16 for (size_t i = 0; i < total - 1; ++i) { 17 ret[i + 1] += ret[i] / 10; 18 ret[i] = ret[i] % 10; 19 } 20 21 size_t begin = total - 1; 22 // 清理开头的0,这里是begin > 0,就是至少保留个位。 23 while (begin > 0 && ret[begin] == 0) 24 begin--; 25 string ans(begin + 1, '0'); 26 for (int i = 0; i <= begin; ++i) { 27 ans[i] += ret[begin-i]; 28 } 29 return ans; 30 } 31 };