LeetCode 0043 - Multiply Strings
# Hints
- 模拟
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Medium |
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
andnum2
is .Both
num1
andnum2
contain only digits0-9
.Both
num1
andnum2
do not contain any leading zero, except the number0
itself.You must not use any built-in BigInteger library or convert the inputs to integer directly.
# 题意
给定两个长度小于 位的非负整数,求它们的乘积。
# 题解
水题,直接模拟大整数乘法的过程即可。
# AC代码
class Solution {
public:
string multiply(const string & num1, const string & num2) {
// 初始化
int n = num1.length();
int m = num2.length();
string res(n + m, '0');
// 求解
int rem = 0;
for (int i = n - 1; i >= 0; i --) {
for (int j = m - 1; j >= 0; j --) {
int x = (num1[i] - '0') * (num2[j] - '0') + (res[i + j + 1] - '0');
res[i + j + 1] = (x % 10) + '0';
res[i + j] += (x / 10);
}
}
// 返回
for (int i = 0; i < n + m; i ++) {
if (res[i] != '0') {
return res.substr(i);
}
}
return "0";
}
};
- 01
- Reading Papers - Kernel Concurrency06-01
- 02
- Linux Kernel - Source Code Overview05-01
- 03
- Linux Kernel - Per-CPU Storage05-01