[leetcode] Multiply Strings
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
https://oj.leetcode.com/problems/multiply-strings/
思路:大数乘法,模拟笔算过程即可。
注意的细节:
- 前导0去掉;
- 结果为0;
代码:
import java.util.Arrays; public class Solution { public String multiply(String num1, String num2) { if (num1 == null || num2 == null || num1.length() == 0 || num2.length() == 0) return null; int n1 = num1.length(); int n2 = num2.length(); char[] str1 = num1.toCharArray(); char[] str2 = num2.toCharArray(); char[] prod = new char[n1 + n2]; Arrays.fill(prod, '0'); int i, j; for (i = 0; i < n1; i++) for (j = 0; j < n2; j++) { prod[i + j] = (char) ((prod[i + j] - '0') + (str1[n1 - 1 - i] - '0') * (str2[n2 - 1 - j] - '0') + '0'); } int c = 0; for (i = 0; i < n1 + n2; i++) { prod[i] = (char) ((prod[i] - '0') + c + '0'); if (prod[i] - '0' + c > 9) { c = (prod[i] - '0') / 10; prod[i] = (char) ((prod[i] - '0') % 10 + '0'); } else c = 0; } StringBuilder sb = new StringBuilder(); i = n1 + n2 - 1; while (i >= 0 && prod[i] == '0') i--; if (i == -1) { sb.append("0"); return sb.toString(); } for (; i >= 0; i--) { sb.append(prod[i]); } return sb.toString(); } public static void main(String[] args) { System.out.println(new Solution().multiply("123", "12345")); System.out.println(new Solution().multiply("0", "123")); } }
第二遍记录:
prod用int数组更方便些
prod[i+j] += ,加号不要忘记了,是多个乘积累加。
注意字符串顺序与索引是反的。
public class Solution { public String multiply(String num1, String num2) { if (num1 == null || num2 == null || num1.length() == 0 || num2.length() == 0) return null; int n1 = num1.length(); int n2 = num2.length(); int[] prod = new int[n1 + n2]; for (int i = 0; i < n1; i++) { for (int j = 0; j < n2; j++) { prod[i + j] += (num1.charAt(n1 - 1 - i) - '0') * (num2.charAt(n2 - 1 - j) - '0'); } } int c = 0; for (int i = 0; i < n1 + n2; i++) { int curVal = prod[i] + c; if (curVal > 9) { c = curVal / 10; prod[i] = curVal % 10; } else { prod[i] = curVal; c = 0; } } StringBuilder sb = new StringBuilder(); int idx = n1 + n2 - 1; while (idx >= 0 && prod[idx] == 0) idx--; if (idx == -1) { sb.append(0); return sb.toString(); } while (idx >= 0) sb.append(prod[idx--]); return sb.toString(); } }
参考:
http://www.cnblogs.com/TenosDoIt/p/3735309.html