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.
对每个数字相乘,记录到一个数组中,然后对这个数字的每个元素进行进位检查。主要相乘的时候要分别从两个数字的最后一位开始,还要记录偏移量。实现如下:
1 public class MultiplyStrings {
2 public String multiply(String num1, String num2) {
3 int length1 = num1.length();
4 int length2 = num2.length();
5 int[] m = new int[length1 + length2];
6 for (int k = length2 - 1, offset2 = 0; k >= 0; k--, offset2++) {
7 for (int i = length1 - 1, offset1 = 0; i >= 0; i--, offset1++) {
8 m[length1 + length2 - 1 - offset1 - offset2] += (num1.charAt(i) - '0') * (num2.charAt(k) - '0');
9 }
10 }
11 int add = 0;
12 for (int t = length1 + length2 - 1; t >= 0; t--) {
13 int value = m[t] + add;
14 add = value / 10;
15 m[t] = value % 10;
16 }
17 StringBuffer sb = new StringBuffer();
18 int w = 0;
19 for (; w < length1 + length2; w++) {
20 if (m[w] != 0) break;
21 }
22 for (int e = w; e < length1 + length2; e++) {
23 sb.append(m[e]);
24 }
25 return sb.length() == 0 ? "0" : sb.toString();
26 }
27 }