FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/PuzzleCoding/src/AddBinary.java at master · wodgithub/algorithm · GitHub
wodgithub
algorithm
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
AddBinary.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
42 lines (38 loc) · 1.15 KB
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
AddBinary.java
Copy path
File metadata and controls
42 lines (38 loc) · 1.15 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
/*
* Given two binary strings, return their sum (also a binary string).
* For example,
* a = "11"
* b = "1"
* Return "100".
*/
public
class
AddBinary
{
public
static
void
main
(
String
[]
args
) {
String
s1
=
"10"
;
String
s2
=
"110"
;
int
result
=
string2Integer
(
s1
,
2
) +
string2Integer
(
s2
,
2
);
System
.
out
.
println
(
toBinary
(
result
));
result
=
Integer
.
parseInt
(
s1
,
2
) +
Integer
.
parseInt
(
s2
,
2
);
System
.
out
.
println
(
Integer
.
toBinaryString
(
result
));
}
public
static
int
string2Integer
(
String
s
,
int
code
) {
int
len
=
s
.
length
();
int
result
=
0
;
for
(
int
i
=
len
-
1
;
i
>=
0
;
i
--) {
int
temp
=
Integer
.
valueOf
(
s
.
charAt
(
i
)-
'0'
);
result
+=
Math
.
pow
(
code
,
len
-
1
-
i
) *
temp
;
}
return
result
;
}
public
static
String
toBinary
(
int
integer
) {
StringBuilder
builder
=
new
StringBuilder
();
int
temp
;
while
(
integer
>=
0
) {
temp
=
integer
;
integer
= (
temp
>>
1
);
builder
.
append
(
temp
%
2
);
if
(
integer
==
0
)
break
;
}
return
builder
.
reverse
().
toString
();
}
}
Back
|
FazBrowse Home
|
New Git URL