Multiply Strings 题解
题目来源:https://leetcode.com/problems/multiply-strings/description/
Description
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution
class Solution {
private:
string multiOneNum(const string& nums, char num) {
int overflow = 0;
string res;
int size = nums.size();
for (int i = size - 1; i >= 0; i--) {
int temp = (nums[i] - '0') * (num - '0');
res.push_back(static_cast<char>((temp + overflow) % 10 + '0'));
overflow = (temp + overflow) / 10;
}
if (overflow > 0)
res.push_back(static_cast<char>(overflow + '0'));
return string(res.rbegin(), res.rend());
}
string addTwoNums(const string& num1, const string& num2) {
int overflow = 0;
string res;
int i, j;
for (i = num1.length() - 1, j = num2.length() - 1;
i >= 0 && j >= 0; --i, --j) {
int temp = (num1[i] - '0') + (num2[j] - '0');
res.push_back(static_cast<char>((temp + overflow) % 10 + '0'));
overflow = (temp + overflow) / 10;
}
while (i >= 0) {
int temp = num1[i--] - '0';
res.push_back(static_cast<char>((temp + overflow) % 10 + '0'));
overflow = (temp + overflow) / 10;
}
while (j >= 0) {
int temp = num2[j--] - '0';
res.push_back(static_cast<char>((temp + overflow) % 10 + '0'));
overflow = (temp + overflow) / 10;
}
if (overflow > 0)
res.push_back(static_cast<char>(overflow + '0'));
while (res.back() == '0')
res.pop_back();
return string(res.rbegin(), res.rend());
}
public:
string multiply(string num1, string num2) {
string& longNum = num1.length() >= num2.length() ?
num1 : num2;
string& shortNum = num1.length() < num2.length() ?
num1 : num2;
int shortLen = shortNum.length();
string res = "0";
if (shortLen == 1 && shortNum[shortLen - 1] == '0')
return res;
for (int i = shortLen - 1; i >= 0; i--) {
if (shortNum[i] == '0')
continue;
string temp = multiOneNum(longNum, shortNum[i]);
int zeroCount = shortLen - 1 - i;
while (zeroCount--) {
temp.push_back('0');
}
if (res == "0")
res = temp;
else
res = addTwoNums(res, temp);
}
return res;
}
};
解题描述
这道题题意是对求出两个用字符串表示的数字相乘结果的字符串表示。上面是我个人的解法,使用的是类似手算乘法的思想,但是在结果字符串上需要多次反转,会大大增加时间复杂度。
更优解法
评论区给出了一种也是类似于手算的解法,但不需要对结果字符串进行反转,原因在于该解法先预留了充足的结果串长度:
class Solution {
public:
string multiply(string num1, string num2) {
int size1 = num1.size(), size2 = num2.size();
string res(size1 + size2, '0');
int i, j, carry; // carry即为进位
for (i = size1 - 1; i >= 0; --i) {
carry = 0;
for (j = size2 - 1; j >= 0; --j) {
int temp = (res[i + j + 1] - '0') +
(num1[i] - '0') * (num2[j] - '0') + carry;
res[i + j + 1] = temp % 10 + '0';
carry = temp / 10;
}
res[i] += carry; // 加上最后的进位
}
int start = res.find_first_not_of('0');
if (start == string::npos)
return "0";
else
return res.substr(start);
}
};