1
+ class Solution {
2
+ public String multiply (String num1 , String num2 ) {
3
+
4
+ if ("0" .equals (num1 ) || "0" .equals (num2 )) {
5
+ return "0" ;
6
+ }
7
+
8
+ int [] res = new int [num1 .length () + num2 .length ()];
9
+
10
+ num1 = reverseString (num1 );
11
+ num2 = reverseString (num2 );
12
+
13
+ for (int i = 0 ; i < num1 .length (); i ++) {
14
+ for (int j = 0 ; j < num2 .length (); j ++) {
15
+ int digit = Integer .valueOf (String .valueOf (num1 .charAt (i ))) * Integer .valueOf (String .valueOf (num2 .charAt (j )));
16
+ res [i + j ] += digit ;
17
+ res [i + j + 1 ] += res [i + j ] / 10 ;
18
+ res [i + j ] = res [i + j ] % 10 ;
19
+ }
20
+ }
21
+
22
+ reverseArrayInPlace (res );
23
+
24
+ // Get the proper starting point to avoid leading zeros
25
+ int startIndex = 0 ;
26
+ while (startIndex < res .length ) {
27
+ if (res [startIndex ] != 0 ) {
28
+ break ;
29
+ }
30
+ startIndex ++;
31
+ }
32
+
33
+ StringBuilder buildResponse = new StringBuilder ();
34
+ for (int i = startIndex ; i < res .length ; i ++) {
35
+ buildResponse .append (res [i ]);
36
+ }
37
+
38
+ return buildResponse .toString ();
39
+ }
40
+
41
+ private String reverseString (String str ) {
42
+ StringBuilder reversedStr = new StringBuilder (str );
43
+ reversedStr .reverse ();
44
+ return reversedStr .toString ();
45
+ }
46
+
47
+ private void reverseArrayInPlace (int [] arr ) {
48
+ for (int i = 0 ; i < arr .length / 2 ; i ++) {
49
+ int temp = arr [i ];
50
+ arr [i ] = arr [arr .length - i - 1 ];
51
+ arr [arr .length - i - 1 ] = temp ;
52
+ }
53
+ }
54
+
55
+ }
0 commit comments