43.Multiply-Strings

43. Multiply Strings

题目地址

https://leetcode.com/problems/multiply-strings/

题目描述

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:
1. The length of both num1 and num2 is < 110.
2. Both num1 and num2 contain only digits 0-9.
3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

代码

Approach #1 Two For-loop

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

      int result[] = new int[len1 + len2];

      int i_n1 = 0;
      int i_n2 = 0;

      for (int i = len1 - 1; i >= 0; i--) {
        int carry = 0;
        int n1 = num1.charAt(i) - '0';

        i_n2 = 0;
        for (int j = len2 - 1; j >= 0; j--) {
          int n2 = num2.charAt(j) - '0';

          int sum = n1 * n2 + result[i_n1 + i_n2] + carry;

          carry = sum / 10;
          result[i_n1 + i_n2] = sum % 10;
          i_n2++;
        }

        if (carry > 0) {
          result[i_n1 + i_n2] += carry;
        }

        i_n1++;
      }

      int i = result.length - 1;
      while (i >= 0 && result[i] == 0) {
        i--;
      }

      if (i == -1) return "0";

      String s = "";
      while (i >= 0) {
        s += (result[i--]);
      }

      return s;
    }
}

Last updated