標籤:style blog color os io ar for div 代碼
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.
大整數的字串乘法,我本來對字串表示的大整數就不是太熟悉,至於溢出該怎麼處理也是不大清楚,所以參考了別人的做法,然後自己憑著印象重做了一次
- 直接乘會溢出,所以每次都要兩個single digit相乘,最大81,不會溢出。
- 比如385 * 97, 就是個位=5 * 7,十位=8 * 7 + 5 * 9 ,百位=3 * 7 + 8 * 9 …
可以每一位用一個Int表示,存在一個int[]裡面。
- 這個數組最大長度是num1.len + num2.len,比如99 * 99,最大不會超過10000,所以4位就夠了。
- 這種個位在後面的,不好做(10的0次方,可惜對應位的數組index不是0而是n-1),
所以乾脆先把string reverse了代碼就清晰好多。
- 最後結果前面的0要清掉。
這裡面的方法比較巧妙,也比較典型,需要掌握。還有需要注意溢出處理,這裡的處理是:如果最高位產生進位carry,那麼直接忽略這個carry
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