題目英文
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 and num2 is < 110.
- Both num1 and num2 contain only digits 0-9.
- Both num1 and num2 do not contain any leading zero, except the number 0 itself.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
題目中文
給定兩個以字符串形式表示的非負整數 num1 和 num2,返回 num1 和 num2 的乘積,它們的乘積也表示爲字符串形式。
示例 1:
輸入: num1 = "2", num2 = "3"
輸出: "6"
示例 2:
輸入: num1 = "123", num2 = "456"
輸出: "56088"
示例 3:
輸入: num1 = "498828660196", num2 = "840477629533"
輸出: "419254329864656431168468"
說明:
- num1 和 num2 的長度小於110。
- num1 和 num2 只包含數字 0-9。
- num1 和 num2 均不以零開頭,除非是數字 0 本身。
- 不能使用任何標準庫的大數類型(比如 BigInteger)或直接將輸入轉換爲整數來處理。
算法實現
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();
}
}
實驗結果
- 狀態:通過
- 311 / 311 個通過測試用例
- 執行用時:132 ms, 在所有 C# 提交中擊敗了 94.74% 的用戶
- 內存消耗:24.1 MB, 在所有 C# 提交中擊敗了 31.82% 的用戶
相關圖文
1. “數組”類算法
- LeetCode實戰:三數之和
- LeetCode實戰:最接近的三數之和
- LeetCode實戰:求衆數
- LeetCode實戰:缺失的第一個正數
- LeetCode實戰:快樂數
- LeetCode實戰:尋找兩個有序數組的中位數
- LeetCode實戰:盛最多水的容器
- LeetCode實戰:刪除排序數組中的重複項
- LeetCode實戰:搜索旋轉排序數組
2. “鏈表”類算法
- LeetCode實戰:兩數相加
- LeetCode實戰:刪除鏈表的倒數第N個節點
- LeetCode實戰:合併兩個有序鏈表
- LeetCode實戰:合併K個排序鏈表
- LeetCode實戰:兩兩交換鏈表中的節點
- LeetCode實戰:旋轉鏈表
- LeetCode實戰:環形鏈表
3. “棧”類算法
4. “隊列”類算法
5. “遞歸”類算法
6. “字符串”類算法
7. “樹”類算法
8. “哈希”類算法
9. “搜索”類算法
10. “動態規劃”類算法
11. “數值分析”類算法