43. Multiply Strings
https://leetcode.com/problems/multiply-strings/discuss/17605/Easiest-JAVA-Solution-with-Graph-Explanation
1 class Solution { 2 public String multiply(String num1, String num2) { 3 if(num1.equals("0") || num2.equals("0")) return "0"; //用equals, 因为可能两个都是"0" 4 int[] res = new int[num1.length() + num2.length()]; 5 int sum = 0, mul = 0; 6 for(int i = num1.length() - 1; i >= 0; i--) { 7 for(int j = num2.length() - 1; j >= 0; j--) { 8 int pos1 = i+j, pos2 = i+j+1; 9 mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); 10 sum = mul + res[pos2]; 11 res[pos1] += sum / 10; // += 因为之后还要加 12 res[pos2] = sum % 10; 13 } 14 } 15 StringBuilder s = new StringBuilder(); 16 for(int pos : res) { 17 if(!(s.length() == 0 && pos == 0)) { 18 s.append(pos); 19 } 20 } 21 return s.toString(); 22 23 } 24 }