题目难度中等,想到分别遍历num1、num2中的数值,但是具体细节没有理清。参考:https://discuss.leetcode.com/topic/30508/easiest-java-solution-with-graph-explanation?page=1
public class TwoSumbin { public String multiply(String num1, String num2) { int m = num1.length(), n = num2.length(); int[] pos = new int[m + n]; 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'); int p1 = i + j; // 十位数 int p2 = i + j + 1; // 个位数 int sum = mul + pos[p2]; pos[p1] += sum / 10; // 开始时是在3,下一个循环pos[3]就是个位数,考虑到了进位 //在篇左侧的数字 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(); } }