1. 程式人生 > 實用技巧 >LeetCode刷題記錄-43

LeetCode刷題記錄-43

借鑑了評論區的大佬的簡化乘法思路,如下圖:

巧妙之處在於使用res陣列來依次接收每一次乘法的部分結果,從而能夠避免較大數字相乘帶來的資料溢位問題

 1  public static String multiply(String num1, String num2) {
 2         //記錄相乘的結果,最大位數不過二者長度之和
 3         int[] res = new int[num1.length() + num2.length()];
 4         //將每一步相乘的結果填入res對應的位置:index
 5         int index;
 6         //
輔助index 7 int cnt = 0; 8 for (int i = num2.length() - 1; i >= 0; i--) { 9 //乘數x 10 int x = num2.charAt(i) - '0'; 11 index = res.length - 1 - cnt; 12 for (int j = num1.length() - 1; j >= 0; j--) { 13 //被乘數y 14 int
y = num1.charAt(j) - '0'; 15 int tmpRes = x * y; 16 res[index] = res[index] + tmpRes % 10; 17 //檢查res[index]的元素是否進位,並且處理進位 18 check(res, index); 19 index--; 20 res[index] = res[index] + tmpRes / 10; 21 check(res, index);
22 } 23 cnt++; 24 } 25 //將陣列形式儲存的結果以字串形式拼接 26 StringBuilder sb = new StringBuilder(); 27 //用來定位第一個非零元素下標 28 index = 0; 29 //是否找到第一個非零元素 30 boolean flag=false; 31 for (int i = 0; i < res.length; i++) { 32 if (res[i] != 0) { 33 index = i; 34 flag=true; 35 break; 36 } 37 } 38 //沒找到第一個非零元素,說明結果全部都是0,自然返回"0" 39 if (flag==false){ 40 return "0"; 41 } 42 for (int i = index; i < res.length; i++) { 43 sb.append(res[i]); 44 } 45 return sb.toString(); 46 } 47 48 private static void check(int[] res, int index) { 49 if (res[index] >= 10) { 50 res[index - 1] += res[index] / 10; 51 res[index] = res[index] % 10; 52 } 53 }

執行結果: