-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path067. Add Binary.java
35 lines (33 loc) · 1.04 KB
/
067. Add Binary.java
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
public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length(), j = b.length();
boolean carry = false;
while (i > 0 || j > 0 || carry) {
char f = --i < 0 ? '0' : a.charAt(i);
char s = --j < 0 ? '0' : b.charAt(j);
if (f == '1' && s == '1') {
if (carry == true) {
sb.insert(0, '1');
} else {
sb.insert(0, '0');
carry = true;
}
} else if (f == '0' && s == '0') {
if (carry == true) {
sb.insert(0, '1');
carry = false;
} else {
sb.insert(0, '0');
}
} else {
if (carry == true) {
sb.insert(0, '0');
} else {
sb.insert(0, '1');
}
}
}
return sb.toString();
}
}