-
Notifications
You must be signed in to change notification settings - Fork 0
/
67. Add Binary
98 lines (90 loc) · 2.92 KB
/
67. Add Binary
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
https://leetcode.com/problems/add-binary/description/
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/
public class Solution {
private static final Logger logger = LogManager.getLogger(Solution.class);
private boolean previousSum = false;
public String addBinary(String a, String b) {
StringBuilder sum = new StringBuilder("");
int lengthA = a.length();
int lengthB = b.length();
if (lengthA > lengthB) {
for (int i = 1; i <= lengthB; i++) {
if (previousSum) {
sum.insert(0, addThreeBinaryDigits(a.charAt(lengthA - i), b.charAt(lengthB - i)));
} else {
sum.insert(0, addTwoBinaryDigits(a.charAt(lengthA - i), b.charAt(lengthB - i)));
}
}
for (int i = lengthB + 1; i <= lengthA; i++) {
if (previousSum) {
sum.insert(0, addTwoBinaryDigits(a.charAt(lengthA - i), '1'));
} else {
sum.insert(0, a.charAt(lengthA - i));
}
}
if (previousSum) {
sum.insert(0, "1");
}
} else {
for (int i = 1; i <= lengthA; i++) {
if (previousSum) {
sum.insert(0, addThreeBinaryDigits(a.charAt(lengthA - i), b.charAt(lengthB - i)));
} else {
sum.insert(0, addTwoBinaryDigits(a.charAt(lengthA - i), b.charAt(lengthB - i)));
}
}
for (int i = lengthA + 1; i <= lengthB; i++) {
if (previousSum) {
sum.insert(0, addTwoBinaryDigits(b.charAt(lengthB - i), '1'));
} else {
sum.insert(0, b.charAt(lengthB - i));
}
}
if (previousSum) {
sum.insert(0, "1");
}
}
return sum.toString();
}
private String addTwoBinaryDigits(char a, char b) {
int sum = a + b - 96;
switch (sum) {
case 0:
previousSum = false;
return "0";
case 1:
previousSum = false;
return "1";
case 2:
previousSum = true;
return "0";
default:
return "Invalid input";
}
}
private String addThreeBinaryDigits(char a, char b) {
int sum = a + b - 95;
switch (sum) {
case 0:
previousSum = false;
return "0";
case 1:
previousSum = false;
return "1";
case 2:
previousSum = true;
return "0";
case 3:
previousSum = true;
return "1";
default:
return "Invalid input";
}
}
}