涉及到的相关题目:415.字符串相加
题目描述:
解法:竖式相加:
num1 为乘数,num2为被乘数。num1与num2的每一位相乘之后再相加。
注意补 0 操作
代码:
class Solution {
public String multiply(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int len1 = num1.length(), len2 = num2.length();
if("0".equals(num1) || "0".equals(num2)){
return "0";
}
int j = len2 - 1;
String a = charMultiStr(String.valueOf(num2.charAt(j)), num1);
int c = 1;
while(j > 0){
j--;
String b = charMultiStr(String.valueOf(num2.charAt(j)), num1);
//补0
int d = c;
sb.append(b);
while(d-- > 0){
sb.append(0);
}
c++;
a = addStrings(a, sb.toString());
sb.delete(0, sb.length());
}
return a;
}
//一个单字符串和一个字符串相乘
public String charMultiStr(String s, String str){
StringBuilder sb = new StringBuilder();
int r = 0, v= 0, a = Integer.valueOf(s);
int i = str.length() - 1;
while(i >= 0){
int b = Integer.valueOf(str.charAt(i) + "");
v = (a * b + r) % 10;
r = (a * b + r) / 10;
sb.append(v);
i--;
}
if(r != 0){
sb.append(r);
}
return sb.reverse().toString();
}
//两个字符串相加【题目:415.字符串相加】
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int i = num1.length() - 1, j = num2.length() - 1;
int r = 0, v= 0;
while(i >= 0 || j >= 0){
int x = i >= 0 ? num1.charAt(i) - '0' : 0;
int y = j >= 0 ? num2.charAt(j) - '0' : 0;
v = (r + x + y) % 10;
r = (r + x + y) >= 10 ? 1:0;
sb.append(v);
i --;
j --;
}
if(r!= 0){
sb.append(r);
}
return sb.reverse().toString();
}
}