classSolution{ public String multiply(String num1, String num2){ // trivial case if (num1.equals("0") || num2.equals("0")) { return"0"; } if (num1.equals("1")) return num2; if (num2.equals("1")) return num1;
// method call optimition int len1 = num1.length(); int len2 = num2.length();
// target result; int[] res = newint[len1 + len2];
for (int i = len1 - 1; i >= 0; i--) { for (int j = len2 - 1; j >= 0; j--) { // multiply single numbers int tmp = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); // len - i - 1 means indentation // add up two single num res[(len1 - i - 1) + len2 - j - 1] += tmp % 10;
// carry int add = res[(len1 - i - 1) + len2 - j - 1] / 10; res[(len1 - i - 1) + len2 - j - 1] %= 10; res[(len1 - i - 1) + len2 - j] += add; res[(len1 - i - 1) + len2 - j] += tmp / 10; } } int fin = res.length - 1; while (res[fin] == 0) fin--; StringBuilder sb = new StringBuilder(); // reverse order to append as string while (fin >= 0) { sb.append((char) (res[fin--] + '0')); } return sb.toString(); } }