-
Notifications
You must be signed in to change notification settings - Fork 1
/
AddBinary.java
60 lines (55 loc) · 1.81 KB
/
AddBinary.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
package com.smlnskgmail.jaman.leetcodejava.easy;
// https://leetcode.com/problems/add-binary/
public class AddBinary {
private final String a;
private final String b;
public AddBinary(String a, String b) {
this.a = a;
this.b = b;
}
public String solution() {
String max = a.length() > b.length() ? a : b;
String min = max == a ? b : a;
int maxPointer = max.length() - 1;
int minPointer = min.length() - 1;
StringBuilder result = new StringBuilder();
int additional = 0;
while (minPointer >= 0) {
char charInMax = max.charAt(maxPointer);
char charInMin = min.charAt(minPointer);
if (additional == 1) {
result.append(charInMax == charInMin ? '1' : '0');
if (charInMax == '0' && charInMin == '0') {
additional = 0;
}
} else {
if (charInMax == '1' && charInMin == '1') {
additional = 1;
result.append('0');
} else {
result.append(charInMax == '1' || charInMin == '1' ? '1' : '0');
}
}
maxPointer--;
minPointer--;
}
while (maxPointer >= 0) {
char charInMax = max.charAt(maxPointer);
if (additional == 1 && charInMax == '1') {
result.append('0');
} else {
if (additional == 1) {
result.append('1');
additional = 0;
} else {
result.append(charInMax);
}
}
maxPointer--;
}
if (additional == 1) {
result.append('1');
}
return result.reverse().toString();
}
}