MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / multiply

Method multiply

src/com/blankj/medium/_0043/Solution.java:12–35  ·  view source on GitHub ↗
(String num1, String num2)

Source from the content-addressed store, hash-verified

10 */
11public class Solution {
12 public String multiply(String num1, String num2) {
13 if (num1.equals("0") || num2.equals("0")) return "0";
14 int l1 = num1.length(), l2 = num2.length(), l = l1 + l2;
15 char[] ans = new char[l];
16 char[] c1 = num1.toCharArray();
17 char[] c2 = num2.toCharArray();
18 for (int i = l1 - 1; i >= 0; --i) {
19 int c = c1[i] - '0';
20 for (int j = l2 - 1; j >= 0; --j) {
21 ans[i + j + 1] += c * (c2[j] - '0');
22 }
23 }
24 for (int i = l - 1; i > 0; --i) {
25 if (ans[i] > 9) {
26 ans[i - 1] += ans[i] / 10;
27 ans[i] %= 10;
28 }
29 }
30 StringBuilder sb = new StringBuilder();
31 int i = 0;
32 for (; ; ++i) if (ans[i] != 0) break;
33 for (; i < ans.length; ++i) sb.append((char) (ans[i] + '0'));
34 return sb.toString();
35 }
36
37 public static void main(String[] args) {
38 Solution solution = new Solution();

Callers 1

mainMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected