1
+ import java .util .ArrayList ;
2
+
3
+ class MultiplyStrings {
4
+ private ArrayList <Integer > addStrings (ArrayList <Integer > num1 , ArrayList <Integer > num2 ) {
5
+ ArrayList <Integer > res = new ArrayList <>();
6
+ int carry = 0 ;
7
+
8
+ for (int i = 0 ; i < num1 .size () || i < num2 .size (); i ++) {
9
+ int digit1 = i < num1 .size () ? num1 .get (i ) : 0 ;
10
+ int digit2 = i < num2 .size () ? num2 .get (i ) : 0 ;
11
+
12
+ int sum = digit1 + digit2 + carry ;
13
+ carry = sum / 10 ;
14
+ res .add (sum % 10 );
15
+ }
16
+
17
+ if (carry != 0 ) {
18
+ res .add (carry );
19
+ }
20
+ return res ;
21
+ }
22
+
23
+ private ArrayList <Integer > multiplyOneDigit (StringBuilder firstNumber , char secondNumberDigit , int numZeros ) {
24
+ ArrayList <Integer > currentResult = new ArrayList <>();
25
+ for (int i = 0 ; i < numZeros ; i ++) currentResult .add (0 );
26
+
27
+ int carry = 0 ;
28
+ for (int i = 0 ; i < firstNumber .length (); i ++) {
29
+ char firstNumberDigit = firstNumber .charAt (i );
30
+ int multiplication = (secondNumberDigit - '0' ) * (firstNumberDigit - '0' ) + carry ;
31
+ carry = multiplication / 10 ;
32
+ currentResult .add (multiplication % 10 );
33
+ }
34
+
35
+ if (carry != 0 ) {
36
+ currentResult .add (carry );
37
+ }
38
+ return currentResult ;
39
+ }
40
+
41
+ public String multiply (String num1 , String num2 ) {
42
+ if (num1 .equals ("0" ) || num2 .equals ("0" )) return "0" ;
43
+
44
+ StringBuilder firstNumber = new StringBuilder (num1 );
45
+ StringBuilder secondNumber = new StringBuilder (num2 );
46
+
47
+ firstNumber .reverse ();
48
+ secondNumber .reverse ();
49
+
50
+ int n = firstNumber .length () + secondNumber .length ();
51
+ ArrayList <Integer > res = new ArrayList <>();
52
+ for (int i = 0 ; i < n ; i ++) res .add (0 );
53
+
54
+ for (int i = 0 ; i < secondNumber .length (); i ++) {
55
+ res = addStrings (multiplyOneDigit (firstNumber , secondNumber .charAt (i ), i ), res );
56
+ }
57
+
58
+ if (res .get (res .size () - 1 ) == 0 ) {
59
+ res .remove (res .size () - 1 );
60
+ }
61
+
62
+ StringBuilder result = new StringBuilder ();
63
+ for (int i = res .size () - 1 ; i >= 0 ; i --) {
64
+ result .append (res .get (i ));
65
+ }
66
+
67
+ return result .toString ();
68
+ }
69
+ }
0 commit comments