forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAdd Binary.java
More file actions
49 lines (40 loc) · 1.33 KB
/
Add Binary.java
File metadata and controls
49 lines (40 loc) · 1.33 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
46
47
48
49
class Solution {
public String addBinary(String a, String b) {
int maxL = Math.max(a.length(), b.length());
if (a.length() < maxL) {
a = String.join("", Collections.nCopies(maxL - a.length(), "0")) + a;
}
if (b.length() < maxL) {
b = String.join("", Collections.nCopies(maxL - b.length(), "0")) + b;
}
int carry = 0;
StringBuilder sb = new StringBuilder("");
for (int i=a.length()-1;i>=0;i--) {
if (a.charAt(i) == '1' && b.charAt(i) == '1') {
if (carry == 1) {
sb.append("1");
}
else {
sb.append("0");
}
carry = 1;
}
else if (a.charAt(i) == '0' && b.charAt(i) == '0') {
sb.append(String.valueOf(carry));
carry = 0;
}
else if (a.charAt(i) != b.charAt(i)) {
if (carry == 1) {
sb.append("0");
}
else {
sb.append("1");
}
}
}
if (carry == 1) {
sb.append("1");
}
return sb.reverse().toString();
}
}