Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly.
publicclass{ public String multiply(String num1, String num2){ if (num1.equals("0") || num2.equals("0")) return"0"; StringBuilder ansBuilder = new StringBuilder(); int len1 = num1.length(); int len2 = num2.length(); int[] ans = newint[len1 + len2]; for (int i = len1 - 1; i > -1; i--) { for (int j = len2 - 1; j > -1; j--) {
int a = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); ans[i + j + 1] += a; } } int c = 0; for (int i = len1 + len2 - 1; i > -1; i--) { int sum = c + ans[i]; ans[i] = sum % 10; c = sum / 10; } int i = 0; while (i < len1 + len2 && ans[i] == 0) i++; for (; i < len1 + len2; i++) { ansBuilder.append((char) (ans[i] + '0')); } return ansBuilder.toString(); } }
近期评论