FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode-algorithms/src/AddBinary.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
/
AddBinary.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
55 lines (47 loc) · 1.51 KB
Breadcrumbs
leetcode-algorithms
/
src
/
AddBinary.java
Copy path
File metadata and controls
55 lines (47 loc) · 1.51 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
50
51
52
53
54
55
import
java
.
util
.
Scanner
;
public
class
AddBinary
{
public
static
void
main
(
String
[]
args
) {
Scanner
scanner
=
new
Scanner
(
System
.
in
);
String
bin1
=
scanner
.
next
();
String
bin2
=
scanner
.
next
();
System
.
out
.
println
(
addBinary
(
bin1
,
bin2
));
}
public
static
String
addBinary
(
String
a
,
String
b
) {
Binary
number1
=
new
Binary
(
a
);
Binary
number2
=
new
Binary
(
b
);
return
number1
.
add
(
number2
).
toString
();
}
private
static
class
Binary
{
private
final
String
number
;
Binary
(
String
number
) {
this
.
number
=
number
;
}
public
int
get
(
int
index
) {
index
=
number
.
length
() -
index
-
1
;
if
(
index
<
0
) {
return
0
;
}
return
number
.
charAt
(
index
) -
48
;
}
public
int
length
() {
return
this
.
number
.
length
();
}
public
Binary
add
(
Binary
other
) {
StringBuilder
result
=
new
StringBuilder
();
int
carry
=
0
;
for
(
int
index
=
0
;
index
<
Math
.
max
(
length
(),
other
.
length
()) ;
index
++) {
int
value
=
this
.
get
(
index
) +
other
.
get
(
index
) +
carry
;
result
.
append
(
value
%
2
);
carry
=
value
/
2
;
}
if
(
carry
>
0
) {
result
.
append
(
carry
);
}
return
new
Binary
(
result
.
reverse
().
toString
());
}
@
Override
public
String
toString
() {
return
this
.
number
;
}
}
}
Back
|
FazBrowse Home
|
New Git URL