Skip to content

Commit 5050f43

Browse files
authored
Create 067. Add Binary.java
1 parent ab851a9 commit 5050f43

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

067. Add Binary.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
public class Solution {
2+
public String addBinary(String a, String b) {
3+
StringBuilder sb = new StringBuilder();
4+
int i = a.length(), j = b.length();
5+
boolean carry = false;
6+
7+
while (i > 0 || j > 0 || carry) {
8+
char f = --i < 0 ? '0' : a.charAt(i);
9+
char s = --j < 0 ? '0' : b.charAt(j);
10+
11+
if (f == '1' && s == '1') {
12+
if (carry == true) {
13+
sb.insert(0, '1');
14+
} else {
15+
sb.insert(0, '0');
16+
carry = true;
17+
}
18+
} else if (f == '0' && s == '0') {
19+
if (carry == true) {
20+
sb.insert(0, '1');
21+
carry = false;
22+
} else {
23+
sb.insert(0, '0');
24+
}
25+
} else {
26+
if (carry == true) {
27+
sb.insert(0, '0');
28+
} else {
29+
sb.insert(0, '1');
30+
}
31+
}
32+
}
33+
return sb.toString();
34+
}
35+
}

0 commit comments

Comments
 (0)