LeetCode实战:43. 字符串相乘
题目
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:
输入:
输入: num1 = "123", num2 = "456"
输出: "56088"
说明:
- num1 和 num2 的长度小于110。
- num1 和 num2 只包含数字 0-9。
- num1 和 num2 均不以零开头,除非是数字 0 本身。
- 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
算法实现
public class Solution {
public string Multiply(string num1, string num2) {
if(num1 == "0" || num2 == "0")
return "0";
int len= num1.Length + num2.Length;
int[] temp = new int[len];
for (int i = num1.Length - 1; i >= 0; i--)
for (int j = num2.Length - 1; j >= 0; j--)
temp[i + j + 1] += (num1[i] - '0')*(num2[j] - '0');
for (int i = len - 1; i>0; i--)
{
if (temp[i]>9)
{
temp[i - 1] += temp[i] / 10;
temp[i] %= 10;
}
}
StringBuilder sb = new StringBuilder();
int s = temp[0] == 0 ? 1:0;
while(s < len)
{
sb.Append(temp[s]);
s++;
}
return sb.ToString();
}
}
思路
利用竖式,先算各个字符的乘积,在进行进位,最后转化为字符串。