forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd Binary.java
More file actions
45 lines (39 loc) · 1.2 KB
/
Add Binary.java
File metadata and controls
45 lines (39 loc) · 1.2 KB
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
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int carry = 0;
int idx1 = a.length() - 1;
int idx2 = b.length() - 1;
while (idx1 >= 0 && idx2 >= 0) {
if (a.charAt(idx1) == '1' && b.charAt(idx2) == '1') {
sb.append(carry == 1 ? 1 : 0);
carry = 1;
}
else if (a.charAt(idx1) == '1' || b.charAt(idx2) == '1') {
sb.append(carry == 0 ? 1 : 0);
}
else {
sb.append(carry);
carry = 0;
}
idx1--;
idx2--;
}
String remainingString = a.length() > b.length() ? a : b;
int idx = Math.max(idx2, idx1);
while (idx >= 0) {
if (remainingString.charAt(idx) == '1') {
sb.append(carry == 1 ? 0 : 1);
}
else {
sb.append(carry);
carry = 0;
}
idx--;
}
if (carry > 0) {
sb.append(carry);
}
return sb.reverse().toString();
}
}