题目:字符串相乘
- 题号:43
- 难度:中等
- https://leetcode-cn.com/problems/multiply-strings/
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数。
示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:
输入: num1 = "123", num2 = "456"
输出: "56088"
示例 3:
输入: num1 = "498828660196", num2 = "840477629533"
输出: "419254329864656431168468"
提示:
- 1 <= num1.length, num2.length <= 200
- num1 和 num2 只能由数字组成。
- num1 和 num2 都不包含任何前导零,除了数字0本身。
实现
C# 语言
public class Solution {
public string Multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0")
return "0";
int len1 = num1.Length;
int len2 = num2.Length;
int len = len1 + len2;
int[] temp = new int[len];
for (int i = len2 - 1; i >= 0; i--)
{
int k = len2 - i;
int b = num2[i] - '0';
for (int j = len1 - 1; j >= 0; j--)
{
int a = num1[j] - '0';
int c = a*b;
temp[len - k] += c%10;
if (temp[len - k] >= 10)
{
temp[len - k] = temp[len - k]%10;
temp[len - k - 1]++;
}
temp[len - k - 1] += c/10;
if (temp[len - k - 1] >= 10)
{
temp[len - k - 1] = temp[len - k - 1]%10;
temp[len - k - 2]++;
}
k++;
}
}
StringBuilder sb = new StringBuilder();
int s = temp[0] == 0 ? 1 : 0;
while (s < len)
{
sb.Append(temp[s]);
s++;
}
return sb.ToString();
}
}
Python 语言
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if num1 == '0' or num2 == '0':
return '0'
len1, len2 = len(num1), len(num2)
len3 = len1 + len2
temp = [0] * len3
for i in range(len2 - 1, -1, -1):
k = len2 - i
b = ord(num2[i]) - ord('0')
for j in range(len1 - 1, -1, -1):
a = ord(num1[j]) - ord('0')
c = a * b
temp[len3 - k] += c % 10
if temp[len3 - k] >= 10:
temp[len3 - k] %= 10
temp[len3 - k - 1] += 1
temp[len3 - k - 1] += c // 10
if temp[len3 - k - 1] >= 10:
temp[len3 - k - 1] %= 10
temp[len3 - k - 2] += 1
k += 1
s = temp[1:] if temp[0] == 0 else temp[:]
s = map(str, s)
return "".join(s)