-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.java
61 lines (55 loc) · 1.5 KB
/
solution.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public String addBinary(String a, String b) {
StringBuilder stringBuilder = new StringBuilder();
int indexA = a.length() - 1;
int indexB = b.length() - 1;
int addon = 0;
while (indexA > -1 && indexB > -1) {
int sum = addon;
if (a.charAt(indexA) == '1') {
sum++;
}
if (b.charAt(indexB) == '1') {
sum++;
}
if (sum == 1 || sum == 3) {
stringBuilder.append('1');
} else {
stringBuilder.append('0');
}
addon = sum >> 1;
indexA--;
indexB--;
}
while (indexA > -1) {
int sum = addon;
if (a.charAt(indexA) == '1') {
sum++;
}
if (sum == 1) {
stringBuilder.append('1');
} else {
stringBuilder.append('0');
}
addon = sum >> 1;
indexA--;
}
while (indexB > -1) {
int sum = addon;
if (b.charAt(indexB) == '1') {
sum++;
}
if (sum == 1) {
stringBuilder.append('1');
} else {
stringBuilder.append('0');
}
addon = sum >> 1;
indexB--;
}
if (addon > 0) {
stringBuilder.append('1');
}
return stringBuilder.reverse().toString();
}
}