LeetCode 43. Multiply Strings
Woodyiiiiiii opened this issue · comments
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
- The length of both num1 and num2 is < 110.
- Both num1 and num2 contain only digits 0-9.
- Both num1 and num2 do not contain any leading zero, except the number 0 itself.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
大数相乘。乘法本质上就是移位的加法,所以我的思路是第一个字符串对第二个字符串的每位字符相乘,左移,将得到的结果相加就是答案。
我的做法如下:
class Solution {
public:
string multiply(string num1, string num2) {
string res;
int n2 = num2.length();
for (int i = n2 - 1; i >= 0; --i) {
string s = singleMul(num1, num2[i] - '0', n2 - i - 1);
res = strAdd(res, s);
}
// 判断字符串是否为全0
for (int i = 0; i < res.length(); ++i) {
if (res[i] != '0') return res;
}
return "0";
}
//相乘函数
string singleMul(string num, int k, int p) {
int n1 = num.length();
int up = 0;
for (int i = n1 - 1; i >= 0; --i) {
char ch = num[i];
int aInt = ch - '0';
ch = (aInt * k + up) % 10 + '0';
up = (aInt * k + up) / 10;
num[i] = ch;
}
//如果还有进位,则要插入到字符串最前
if (up) {
num.insert(0, 1, up + '0');
}
while (p > 0) {
num.push_back('0');
--p;
}
return num;
}
//字符串相加函数
string strAdd(string res, string s) {
string result;
int resLen = res.length(), sLen = s.length();
if (resLen == 0) return s;
int i = resLen - 1, j = sLen - 1;
int up = 0;
while (i >= 0 && j >= 0) {
int a = (res[i] - '0') + (s[j] - '0') + up;
result.push_back(a % 10 + '0');
up = a / 10;
--i;
--j;
}
while (i >= 0) {
char ch = (res[i] - '0' + up) % 10 + '0';
up = (res[i] - '0' + up) / 10;
result.push_back(ch);
--i;
}
while (j >= 0) {
char ch = (s[j] - '0' + up) % 10 + '0';
up = (s[j] - '0' + up) / 10;
result.push_back(ch);
--j;
}
//不要忘了也要算进位
if (up != 0) result.push_back(up + '0');
i = 0;
j = result.length() - 1;
//因为顺序是反着的,所以字符串要翻转一遍
while (i < j) {
char temp = result[i];
result[i] = result[j];
result[j] = temp;
++i;
--j;
}
return result;
}
};
遇到的困难点:
- Java对字符串更改某个字符很麻烦,不如C++的STL方便
- C++的string类的函数,比如insert, pushback等
- 相加函数中要注意进位和最后的反转(其实可以前插就不用翻转了)
- 最后要判断字符串是否全0
参考资料: