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.
num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]` //参考大神的code https://discuss.leetcode.com/topic/30508/easiest-java-solution-with-graph-explanation
public class Solution { public String multiply(String num1, String num2) { int m = num1.length(); int n = num2.length(); int[] pos = new int[m+n]; for(int i = m -1 ; i>= 0; i--){ for(int j = n-1; j >= 0; j--){ int pos1 = i + j; int pos2 = i+j+1; int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int sum = mul + pos[pos2]; pos[pos2] = sum % 10; pos[pos1] += sum /10; } } StringBuilder sb = new StringBuilder(); for(int p : pos) { if(!(sb.toString().length() == 0 && p == 0)) //"0" * "0" = "00" sb.append(p); } return sb.toString().length() == 0? "0":sb.toString() ; } }