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 }
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 }