Skip to content

43. Multiply Strings

Jacky Zhang edited this page Sep 9, 2016 · 2 revisions

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note:

  • The numbers can be arbitrarily large and are non-negative.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

解题思路为:

Start from right to left, perform multiplication on every pair of digits, and add them together.

`num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]` 
public class Solution {
    public String multiply(String num1, String num2) {
        if(num1.equals("0") || num2.equals("0")) return "0";
        int m = num1.length();
        int n = num2.length();
        int[] res = new int[m+n];
        for(int i = m-1; i >= 0; i--) {
            for(int j = n-1; j >= 0; j--) {
                int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                int p1 = i + j, p2 = i + j + 1;
                int sum = mul + res[p2];
                res[p1] += sum / 10;
                res[p2] = sum % 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        for(int r : res) {
            if(!(sb.length() == 0 && r == 0)) sb.append(r);
        }
        return sb.toString();
    }
}
Clone this wiki locally