题目讲解
43. 字符串相乘
算法讲解
class Solution {
public:void AddZero(string& temp, int cnt) {while (cnt--) {temp += '0';}
}string Add(string num1, string num2) {string result;int carry = 0;int i = num1.size() - 1;int j = num2.size() - 1;while (i >= 0 || j >= 0 || carry > 0) {int sum = carry;if (i >= 0) {sum += num1[i] - '0';i--;}if (j >= 0) {sum += num2[j] - '0';j--;}carry = sum / 10;sum = sum % 10;result = to_string(sum) + result;}if (carry > 0) {result = std::to_string(carry) + result;}return result;
}string multiply(string num1, string num2) {if(num1 == "0" || num2 == "0")return "0";int len1 = num1.size();int len2 = num2.size();// num1表示长的字符串if (len1 < len2)num1.swap(num2);string ret;// 字符串相乘for (int i = num2.size() - 1; i >= 0; i--) {int string_num = num2[i] - '0';int flag = 0;string temp;for (int j = num1.size() - 1; j >= 0; j--) {int sum = string_num * (num1[j] - '0') + flag;flag = sum / 10;sum %= 10;temp = to_string(sum) + temp;}// 计算最后一位的进位if (flag)temp = to_string(flag) + temp;// 处理末尾的0 和 相加AddZero(temp, num2.size() - 1 - i);ret = Add(ret, temp);}return ret;
}
};