leetcode 0043
说明
只是为了记录一下,不求多快,也不深究。
会简要描述思路,代码中不写注释。
如碰到不会做的用了别人代码会在博客中标出。
题目描述
思路
就是模拟一下手算乘法。
先把每一位结果存在字符数组里。
变成StringBuilder,操作方便一点。
前面多补个0,省得最后进位的判断,开头要是0就把0去了。
一些边界条件注意一下,比如0x0这些。
还是写的又臭又长。。。
class Solution {
public String multiply(String num1, String num2) {
String small = num1.length() <= num2.length() ? num1 : num2;
String big = num1.length() > num2.length() ? num1 : num2;
char[][] mul = new char[small.length()][big.length() + 1];
int ones = 0, tens = 0;
for (int i = small.length() - 1; i >= 0; i--) {
for (int j = big.length() - 1; j >= 0; j--) {
int temp = (small.charAt(i) - '0') * (big.charAt(j) - '0') + tens;
ones = temp % 10;
tens = temp / 10;
mul[i][j + 1] = (char) (ones + 48);
if (j == 0) {
mul[i][0] = (char) (tens + 48);
}
}
ones = 0;
tens = 0;
}
StringBuilder[] sb = new StringBuilder[small.length()];
for (int i = 0; i < small.length(); i++) {
sb[i] = new StringBuilder();
for (int j = 0; j <= big.length(); j++) {
sb[i].append(mul[i][j]);
}
int k = i;
while (k >= 0) {
sb[i].insert(0, '0');
k--;
}
int l = i;
while (l < small.length() - 1) {
sb[i].append('0');
l++;
}
}
ones = 0;
tens = 0;
StringBuilder res = new StringBuilder();
for (int i = sb[0].length() - 1; i >= 0; i--) {
int temp = 0;
for (StringBuilder s : sb) {
temp += s.charAt(i) - '0';
}
temp += tens;
ones = temp % 10;
tens = temp / 10;
res.insert(0, ones);
}
while (res.charAt(0) == '0' && res.length() != 1) {
res.deleteCharAt(0);
}
return res.toString();
}
}