FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode-algorithms/src/MultiplyStrings.java at master · anishLearnsToCode/leetcode-algorithms · GitHub
anishLearnsToCode
/
leetcode-algorithms
Public
Notifications
You must be signed in to change notification settings
Fork
17
Star
98
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode-algorithms
/
src
/
MultiplyStrings.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
49 lines (43 loc) · 1.72 KB
Breadcrumbs
leetcode-algorithms
/
src
/
MultiplyStrings.java
Copy path
File metadata and controls
49 lines (43 loc) · 1.72 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// https://leetcode.com/problems/multiply-strings
// T: O(|num1| * |num2|)
// S: O(|num1| + |num2|)
public
class
MultiplyStrings
{
private
static
final
String
ZERO
=
"0"
;
private
static
final
String
ONE
=
"1"
;
public
String
multiply
(
String
num1
,
String
num2
) {
if
(
ZERO
.
equals
(
num1
) ||
ZERO
.
equals
(
num2
))
return
ZERO
;
if
(
ONE
.
equals
(
num1
))
return
num2
;
if
(
ONE
.
equals
(
num2
))
return
num1
;
StringBuilder
result
=
new
StringBuilder
(
ZERO
);
for
(
int
i
=
num2
.
length
() -
1
;
i
>=
0
;
i
--) {
result
=
add
(
result
,
multiply
(
num1
,
num2
.
charAt
(
i
) -
'0'
,
num2
.
length
() -
i
-
1
));
}
return
result
.
toString
();
}
private
StringBuilder
multiply
(
String
number
,
int
digit
,
int
factor
) {
final
StringBuilder
result
=
new
StringBuilder
();
int
carry
=
0
;
for
(
int
i
=
number
.
length
() -
1
;
i
>=
0
;
i
--) {
int
val
= (
number
.
charAt
(
i
) -
'0'
) *
digit
+
carry
;
result
.
append
(
val
%
10
);
carry
=
val
/
10
;
}
if
(
carry
>
0
)
result
.
append
(
carry
);
return
result
.
reverse
().
append
(
ZERO
.
repeat
(
factor
));
}
private
StringBuilder
add
(
StringBuilder
a
,
StringBuilder
b
) {
final
StringBuilder
result
=
new
StringBuilder
();
int
carry
=
0
;
for
(
int
i
=
a
.
length
() -
1
,
j
=
b
.
length
() -
1
;
i
>=
0
||
j
>=
0
;
i
--,
j
--) {
int
val
=
getDigit
(
a
,
i
) +
getDigit
(
b
,
j
) +
carry
;
result
.
append
(
val
%
10
);
carry
=
val
/
10
;
}
if
(
carry
>
0
)
result
.
append
(
carry
);
return
result
.
reverse
();
}
private
int
getDigit
(
StringBuilder
string
,
int
index
) {
if
(
index
<
0
)
return
0
;
return
string
.
charAt
(
index
) -
'0'
;
}
}
Back
|
FazBrowse Home
|
New Git URL