思路:
模拟竖向除法,一些边界情况需要考虑到,需要提前把相乘结果的最大位数预留出来,最后根据实际情况进行缩减,同时进位的时候也需要考虑最高位的进位。
代码
class Solution { public: string multiply(string num1, string num2) {
if (num1.size() < num2.size()) { swap(num1, num2); } int l1 = num1.size(), l2 = num2.size(); string ret(l1 + l2, '0'); for (int i = l2 - 1; i >= 0; -- i) { int count = 0; for (int j = l1 - 1; j >= 0; -- j) { int sum = (num1[j] - '0') * (num2[i] - '0') + count; sum += (ret[(l2 - i) + (l1 - j) - 2] - '0'); ret[(l2 - i) + (l1 - j) - 2] = '0' + sum % 10; count = sum / 10; } if (count != 0) { ret[(l2 - i) + (l1 - -1) - 2] = '0' + count; } } while (ret.size() > 1 && ret.back() == '0') { ret.pop_back(); } reverse(ret.begin(), ret.end()); return ret;
} };
|