43.字符串相乘
方法一:做加法,模拟竖式乘法的方法计算乘积
class Solution {public String multiply(String num1, String num2) {if(num1.equals("0") || num2.equals("0")){return "0";}String res = "0";//num2逐位与num1相乘for(int i = num2.length() - 1;i >= 0;i--){int carry = 0;//保存num2第i位数字与num1相乘的结果StringBuilder tmp = new StringBuilder();//补0for(int j =0;j<num2.length() - 1- i;j++){tmp.append(0);}int n2 = num2.charAt(i) - '0';//num2的第i位数字n2与num1相乘for(int j = num1.length() - 1;j>=0 || carry!=0 ; j--){int n1 = j < 0 ? 0 : num1.charAt(j) -'0';int product = (n1 * n2 + carry) % 10;tmp.append(product);carry = (n1 * n2 + carry) /10;}res = addStrings(res,tmp.reverse().toString());}return res;}//对两个字符串数字进行相加,返回字符串形式的和public String addStrings(String num1,String num2){StringBuilder builder = new StringBuilder();int carry = 0; //进位for(int i = num1.length() - 1, j = num2.length() -1; i>=0||j>=0 || carry!=0;i--,j--){int x = i < 0 ? 0:num1.charAt(i) - '0';int y = j < 0 ? 0:num2.charAt(j) - '0';int sum = (x + y + carry) % 10;builder.append(sum);carry = (x + y + carry) / 10;}return builder.reverse().toString();}
}
方法二:做乘法
class Solution {public String multiply(String num1, String num2) {if(num1.equals("0") || num2.equals("0")){return "0";}int len1 = num1.length(),len2 = num2.length();int[] ans = new int[len1 + len2];for(int i = len1 - 1 ;i>=0;i--){int value1 = num1.charAt(i) - '0';for(int j = len2 - 1;j>=0;j--){int value2 = num2.charAt(j) - '0';int sum = ans[i+j+1]+ value1*value2;ans[i+j+1] = sum % 10;ans[i+j] += sum/10;}}StringBuilder sb=new StringBuilder();for(int i=0;i<ans.length;i++){if(i==0 && ans[i]==0){continue;}sb.append(ans[i]);}return sb.toString();}
}