Home LeetCode. 43. Multiply Strings
Post
Cancel

LeetCode. 43. Multiply Strings

image

[Link] https://leetcode.com/problems/multiply-strings/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
    public String multiply(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int len1 = num1.length(), len2 = num2.length();
        int[] arr = new int[len1 + len2];
        for(int i = 0; i < len1; i++)
            for(int j = 0; j < len2; j++)
                arr[i + j + 1] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');

        for(int i = arr.length - 1; i >= 0; i--) {
            if(arr[i] == -1) continue;
            if(arr[i] > 9) {
                int remainder = arr[i] / 10;
                arr[i - 1] += remainder;
                arr[i] -= 10 * remainder;
            }
        }
        boolean zero = true;
        for(int i = 0; i <= len1 + len2 - 1; i++)  {
            if(zero) {
                if(arr[i] == 0) continue;
                else zero = false;
            }
            if(!zero) sb.append(Integer.toString(arr[i]));
        }
        return sb.length() == 0 ? "0" : sb.toString();
    }
}
This post is licensed under CC BY 4.0 by the author.