题解 | #大数乘法#
大数乘法
https://www.nowcoder.com/practice/c4c488d4d40d4c4e9824c3650f7d5571?tpId=117&tqId=37843&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26pageSize%3D50%26search%3D%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D117&difficulty=undefined&judgeStatus=undefined&tags=&title=
每次看到模拟题目就想睡觉
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param s string字符串 第一个整数
* @param t string字符串 第二个整数
* @return string字符串
*/
string solve(string s, string t) {
if (s == "0" || t == "0") {
return "0";
}
// 最高位有进位则长度等于两者之和,不然长度减一,这里存放中间结果,不需要考虑最高位进位
std::vector<int> tmp(s.size() + t.size() - 1, 0);
for (int i = s.size() - 1; i >= 0; --i) {
for (int j = t.size() - 1; j >= 0; --j) {
// 对应位相乘结果的累加和
tmp[i + j] += (s[i] - '0') * (t[j] - '0');
}
}
int carry = 0;
std::string res;
for (int i = tmp.size() - 1; i >= 0; --i) {
int num = tmp[i] + carry;
res.push_back('0' + (num % 10));
carry = num / 10;
}
if (carry) {
res.push_back('0' + carry);
}
std::reverse(res.begin(), res.end());
return res;
}
};