给定两个以字符串形式表示的非负整数 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/multiply-strings 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

我的解

还可优化,用数组代替list,看评论区

  1. class Solution {
  2. public String multiply(String num1, String num2) {
  3. if (num1.equals("0") || num2.equals("0")) return "0";
  4. char[] cs1 = num1.toCharArray();
  5. char[] cs2 = num2.toCharArray();
  6. if (cs1.length < cs2.length) {
  7. char[] cs = cs1;
  8. cs1 = cs2;
  9. cs2 = cs;
  10. }
  11. LinkedList<LinkedList<Integer>> ls = new LinkedList<>();
  12. for (int i = cs2.length - 1; i > -1; i--) {
  13. int carry = 0;
  14. LinkedList<Integer> lkl = new LinkedList<>();
  15. for (int j = cs1.length - 1; j > -1; j--) {
  16. int val = (cs2[i] - '0') * (cs1[j] - '0') + carry;
  17. int remain = val % 10;
  18. lkl.addFirst(remain);
  19. carry = val / 10;
  20. if (j == 0 && carry != 0) lkl.addFirst(carry);
  21. }
  22. ls.addFirst(lkl);
  23. }
  24. String result = "";
  25. LinkedList<Integer> up = ls.removeLast();
  26. while (!ls.isEmpty()) {
  27. LinkedList<Integer> nls = new LinkedList<>();
  28. LinkedList<Integer> down = ls.removeLast();
  29. result = up.removeLast() + result;
  30. int carry = 0;
  31. while (up.size() > 0 || down.size() > 0) {
  32. int val = (up.isEmpty() ? 0 : up.removeLast()) + (down.isEmpty() ? 0 : down.removeLast()) + carry;
  33. int remain = val % 10;
  34. nls.addFirst(remain);
  35. carry = val / 10;
  36. }
  37. if (carry != 0) nls.addFirst(carry);
  38. up = nls;
  39. }
  40. while (!up.isEmpty()){
  41. result = up.removeLast() + result;
  42. }
  43. return result;
  44. }
  45. }

优解 - 绝

class Solution {
    public String multiply(String num1, String num2) {
        if(num1.equals("0") || num2.equals("0")) return "0";
        int m = num1.length(), n = num2.length();

        int [] ansArr = new int[m + n];
        for(int i = m -1; i >= 0; i--){
            int x = num1.charAt(i) - '0';
            for(int j = n -1; j >= 0; j--){
                int y = num2.charAt(j) - '0';
                ansArr[i + j + 1] += x * y;
            }
        }
        for(int i = m + n -1; i > 0; i--){
            ansArr[i -1] += ansArr[i] / 10;
            ansArr[i] = ansArr[i] % 10;
        }
        int index = ansArr[0] == 0 ? 1:0;
        StringBuffer product = new StringBuffer();
        while(index < m+n){
            product.append(ansArr[index]);
            index++;
        }
        return product.toString();

    }
}