Multiply String

By | August 30, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

leetcode 43.

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.

Solution. An awesome solution is from this post.

  1. length of new string is len1 + len2.
  2. iterates each element in num1 and num2 from lower to higher position.
  3. num1[i] * num2[j] will be placed at [i + j], [i + j + 1] position.

multiplystring

public String multiply(String num1, String num2) {
    int[] digit = new int[num1.length() + num2.length()];
    for (int i = num1.length() - 1; i >= 0; i--) {
        for (int j = num2.length() - 1; j >= 0; j--) {
            int posHigh = i + j, posLow = i + j + 1;
            int curr = (num1.charAt(i) - '0') * (num2.charAt(j) - '0') + digit[posLow];
            digit[posLow]  = curr % 10;
            digit[posHigh] += curr / 10;
        }
    }
    StringBuffer sb = new StringBuffer();
    for (int i : digit) {
        if (!(sb.length() == 0 && i == 0)) {
            sb.append(i);
        }
    }
    return sb.length() == 0 ? "0" : sb.toString();
}

Check my code on github.