[LeetCode] #43 字串相乘
阿新 • • 發佈:2021-10-15
[LeetCode] #43 字串相乘
給定兩個以字串形式表示的非負整數num1
和num2
,返回num1
和num2
的乘積,它們的乘積也表示為字串形式。
輸入: num1 = "123", num2 = "456"
輸出: "56088"
模擬乘法的過程
class Solution { public String multiply(String num1, String num2) { if(num1.equals("0") || num2.equals("0")) return "0"; String res = "0"; List<StringBuilder> list = newArrayList(); char[] char1 = num1.toCharArray(); char[] char2 = num2.toCharArray(); int l1 = num1.length(), l2 = num2.length(); int temp = 0, carry = 0, cur = 0, count = -1; for(int i = l1-1; i >= 0; i--){ StringBuilder sb = new StringBuilder(); carry= 0; for(int j = l2-1; j >= 0; j--){ temp = (char1[i] - '0') * (char2[j] - '0') + carry; sb.append(temp % 10); carry = temp / 10; } count++; if(carry != 0) sb.append(carry); sb.reverse();for(int k = count; k > 0; k--){ sb.append(0); } System.out.println(sb.toString()); res = addStrings(res, sb.toString()); } return res; } public String addStrings(String num1, String num2) { int i = num1.length() - 1, j = num2.length() - 1, add = 0; StringBuffer ans = new StringBuffer(); while (i >= 0 || j >= 0 || add != 0) { int x = i >= 0 ? num1.charAt(i) - '0' : 0; int y = j >= 0 ? num2.charAt(j) - '0' : 0; int result = x + y + add; ans.append(result % 10); add = result / 10; i--; j--; } ans.reverse(); return ans.toString(); } }
優化,使用陣列代替字串儲存
class Solution { public String multiply(String num1, String num2) { if (num1.equals("0") || num2.equals("0")) { return "0"; } int m = num1.length(), n = num2.length(); int[] ansArr = new int[m + n]; for (int i = m - 1; i >= 0; i--) { int x = num1.charAt(i) - '0'; for (int j = n - 1; j >= 0; j--) { int y = num2.charAt(j) - '0'; ansArr[i + j + 1] += x * y; } } for (int i = m + n - 1; i > 0; i--) { ansArr[i - 1] += ansArr[i] / 10; ansArr[i] %= 10; } int index = ansArr[0] == 0 ? 1 : 0; StringBuffer ans = new StringBuffer(); while (index < m + n) { ans.append(ansArr[index]); index++; } return ans.toString(); } }
知識點:無
總結:無