# 43. Multiply Strings

43 Multiply Strings

``````public class Solution {
public String multiply(String num1, String num2) {
int m = num1.length(), n = num2.length();
int[] pos = new int[m + n]; // 0是最高位

for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
// p1代表进位， p2表示本位。
int p1 = i + j, p2 = i + j + 1;
// sum 就是本位的乘积加上本位已有的值。
int sum = mul + pos[p2];
// 进位就是除以10的余数
pos[p1] += sum / 10;
// 本位就是剩下的个位数。
pos[p2] = (sum) % 10;
}
}

StringBuilder sb = new StringBuilder();
for(int p : pos) if(!(sb.length() == 0 && p == 0)) sb.append(p);
return sb.length() == 0 ? "0" : sb.toString();
}
}``````

``````public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();

char[] cha = a.toCharArray();
char[] chb = b.toCharArray();
int i = cha.length-1, j = chb.length -1, carry = 0;

while(i >=0 || j>=0) {
int vala = i >= 0 ? cha[i--] - '0' : 0;
int valb = j >= 0 ? chb[j--] - '0' : 0;
int cur = vala+ valb + carry;
sb.append(cur%2);
carry = cur/2;
}
if(carry == 1) sb.append(1);
return sb.reverse().toString();
}
}``````

``````public class Solution {
public String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();

for(int i = num1.length() -1, j = num2.length()-1, carry = 0; i >= 0 || j >= 0 || carry == 1; i--, j--){
int x = i < 0 ? 0 : num1.charAt(i) - '0';
int y = j < 0 ? 0 : num2.charAt(j) - '0';
sb.append((x+y+carry)%10);
carry = (x+y+carry)/10;
}

return sb.reverse().toString();
}
}``````

12 声望
4 粉丝
0 条评论