leetcode——43. 字符串相乘
public String multiply(String num1, String num2) { if(num1.equals("0") || num2.equals("0")){ return "0"; } String res = ""; if(num1.length()<num2.length()){ String temp = num1; num1 = num2; num2 = temp; } for(int i = num2.length()-1;i>=0;i--){ String str = multiply(num1,num2,i); res = add(res,str); } return res; } private String add(String res, String str) { if(res.equals("")) return str; int len1 = res.length(); int len2 = str.length(); int len = Math.max(len1,len2); if(len1<len){ int x = len-len1; String t = ""; for(int i = 0;i<x;i++){ t += "0"; } res = t + res; }else if(len2<len){ int x = len-len2; String t = ""; for(int i = 0;i<x;i++){ t += "0"; } str = t + str; } int cur = 0; String r = ""; for(int i = len-1;i>=0;i--){ int m = res.charAt(i)-'0'+str.charAt(i) - '0'; r = (m+cur)%10 + r; cur = (m+cur)/10; } if(cur!=0){ return cur + r; } return r; } private String multiply(String num1,String num2,int index){ int cur = 0; String str = ""; for(int i = num1.length()-1;i>=0;i--){ int x = (num1.charAt(i)-'0')*(num2.charAt(index)-'0'); str = (x+cur)%10 + str; cur = (x+cur)/10; } if(cur!=0){ str = cur+str; } for(int j = 0;j<num2.length()-index-1;j++){ str += '0'; } return str; }
——2020.9.2
我的前方是万里征途,星辰大海!!