class
GFG {
public
static
String multiply(String a, String b)
{
boolean
flag1 =
false
;
boolean
flag2 =
false
;
a = a.trim();
b = b.trim();
if
(a.charAt(
0
) ==
'-'
) {
a = a.replace("-", "");
flag1 =
true
;
}
if
(b.charAt(
0
) ==
'-'
) {
b = b.replace("-", "");
flag2 =
true
;
}
String out = "";
int
row = a.length();
int
column = b.length();
int
[][] c =
new
int
[row][column];
for
(
int
i =
0
; i < row; i++) {
for
(
int
j =
0
; j < column; j++) {
int
n1
= Character
.getNumericValue(
a.charAt(i));
int
n2
= Character
.getNumericValue(
b.charAt(j));
c[i][j] = n1 * n2;
}
}
int
[] sum =
new
int
[row + column -
1
];
int
m =
0
;
for
(
int
i =
0
; i < row; i++) {
int
k = i;
int
add =
0
;
for
(
int
j =
0
; j < column && k >=
0
; j++, k--) {
add = add + c[k][j];
}
sum[m] = add;
m = m +
1
;
}
for
(
int
k =
1
; k < column; k++) {
int
i = row -
1
;
int
j = k;
int
add =
0
;
while
(j < column && i >=
0
) {
add = add + c[i][j];
j = j +
1
;
i = i -
1
;
}
sum[m] = add;
m = m +
1
;
}
if
(sum.length !=
1
) {
String temp
= Integer
.toString(
sum[sum.length -
1
]);
int
t =
0
;
for
(
int
n = sum.length -
1
; n >=
1
; n--) {
t = t + sum[n];
temp = Integer.toString(t);
if
(temp.length() >
1
) {
String str = temp.substring(
0
, temp.length() -
1
);
t = Integer.parseInt(str);
}
else
{
t =
0
;
}
out = temp.charAt(temp.length() -
1
) + out;
}
t = t + sum[
0
];
temp = Integer.toString(t);
out = temp + out;
}
else
{
out = out + sum[
0
];
}
StringBuffer s =
new
StringBuffer(out);
for
(
int
i =
0
; i < s.length() -
1
; i++) {
if
(s.charAt(i) ==
'0'
) {
s.deleteCharAt(i);
i = i -
1
;
}
else
{
break
;
}
}
out = s.toString();
if
(!out.equals("
0
")) {
if
(flag1 ==
true
&& flag2 ==
false
) {
out = "-" + out;
}
else
if
(flag2 ==
true
&& flag1 ==
false
) {
out = "-" + out;
}
}
return
out;
}
public
static
void
main(String args[])
{
String str1 = "
123456789
";
String str2 = "
987654321
";
System.out.println(multiply(str1, str2));
str1 = "
1235421415454545454545454544
";
str2 = "
1714546546546545454544548544544545
";
System.out.println(multiply(str1, str2));
}
}