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.
I was not very familiar with the large integers represented by strings in the multiplication of large integers, and it is not clear how to handle overflow. So I have referred to others' practices, then I redo it with my impressions.
- Direct multiplication overflows, so two single digit pairs must be multiplied each time. The maximum value is 81, and no overflow occurs.
- For example, 385*97 means a single digit = 5*7, ten digits = 8*7 + 5*9, and a hundred digits = 3*7 + 8*9...
Each digit can be represented by an int, which exists in an int.
- The maximum length of this array is num1.len + num2.len. For example, 99*99, the maximum length is no more than 10000, so four digits are enough.
- This kind of BIT is behind, it is not easy to do (10 to the power of 0, but unfortunately the index of the corresponding bit array is not 0 but N-1 ),
So the code of string reverse is much clearer first.
- The first 0 in the final result must be cleared.
The methods here are clever and typical and need to be mastered. Also pay attention to the overflow processing. Here, the processing is: if the highest bit produces carry, then ignore this carry directly.
1 public class Solution { 2 public String multiply(String num1, String num2) { 3 num1 = new StringBuffer(num1).reverse().toString(); 4 num2 = new StringBuffer(num2).reverse().toString(); 5 int[] n1 = new int[num1.length()]; 6 int[] n2 = new int[num2.length()]; 7 int[] temp = new int[num1.length() + num2.length()]; 8 for (int i = 0; i < num1.length(); i++) { 9 n1[i] = (int)(num1.charAt(i) - ‘0‘); 10 for (int j = 0; j < num2.length(); j++) {11 n2[j] = (int)(num2.charAt(j) - ‘0‘);12 temp[i + j] += n1[i] * n2[j]; 13 }14 }15 16 StringBuffer sb = new StringBuffer();17 int digit = 0;18 int carry = 0;19 for (int k = 0; k < temp.length; k++) {20 digit = temp[k] % 10;21 carry = temp[k] / 10;22 sb.insert(0, digit);23 if (k < temp.length - 1) {24 temp[k + 1] += carry;25 }26 }27 28 while (sb.length() > 0 && sb.charAt(0) == ‘0‘) {29 sb.deleteCharAt(0);30 }31 return sb.length() == 0? "0" : sb.toString();32 }33 }
Leetcode: multiply strings