LeetCode实战:字符串相乘

题目英文

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. “数组”类算法

2. “链表”类算法

3. “栈”类算法

4. “队列”类算法

5. “递归”类算法

6. “字符串”类算法

7. “树”类算法

8. “哈希”类算法

9. “搜索”类算法

10. “动态规划”类算法

11. “数值分析”类算法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章