-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode67.java
More file actions
110 lines (102 loc) · 3.47 KB
/
LeetCode67.java
File metadata and controls
110 lines (102 loc) · 3.47 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
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
99
100
101
102
103
104
105
106
107
108
109
110
import java.util.LinkedList;
import util.PrintUtil;
public class LeetCode67 {
public static void main(String[] args) {
String a;
String b;
// 输入:a = "11", b = "1"
// 输出:"100"
a = "11";
b = "1";
System.out.println(a + " " + b);
System.out.println(new Solution67_2().addBinary(a, b));
PrintUtil.printDivider();
// 输入:a = "1010", b = "1011"
// 输出:"10101"
a = "1010";
b = "1011";
System.out.println(a + " " + b);
System.out.println(new Solution67_2().addBinary(a, b));
PrintUtil.printDivider();
}
}
class Solution67_1 {
// NOTE: 这个版本过于复杂,其实可以同时使用i和j来索引
public String addBinary(String a, String b) {
boolean carry = false;
LinkedList<Character> list = new LinkedList<Character>();
StringBuilder sb = new StringBuilder();
int length1 = a.length();
int length2 = b.length();
for (int i = Math.max(length1, length2) - 1; i >= 0; i--) {
char s1, s2;
// 先获得每个索引对应的字符,长度不够默认为'0'
if (length1 == length2) {
s1 = a.charAt(i);
s2 = b.charAt(i);
} else if (length1 < length2) {
if (i - (length2 - length1) >= 0) {
s1 = a.charAt(i - (length2 - length1));
s2 = b.charAt(i);
} else {
s1 = '0';
s2 = b.charAt(i);
}
} else {
if (i - (length1 - length2) >= 0) {
s1 = a.charAt(i);
s2 = b.charAt(i - (length1 - length2));
} else {
s1 = a.charAt(i);
s2 = '0';
}
}
// System.out.println(String.format("s1: %c s2: %c carry: %b", s1, s2, carry));
if (carry) {
if (s1 == '0' && s2 == '0') {
list.addFirst('1');
carry = false;
} else if (s1 == '1' && s2 == '1') {
list.addFirst('1');
carry = true;
} else {
list.addFirst('0');
carry = true;
}
} else {
if (s1 == '0' && s2 == '0') {
list.addFirst('0');
carry = false;
} else if (s1 == '1' && s2 == '1') {
list.addFirst('0');
carry = true;
} else {
list.addFirst('1');
carry = false;
}
}
}
if (carry) {
list.addFirst('1');
}
for (Character c : list) {
sb.append(c);
}
// NOTE: 也可以直接使用sb的reverse()函数
return sb.toString();
}
}
class Solution67_2 {
public String addBinary(String a, String b) {
StringBuilder ans = new StringBuilder();
int carry = 0;
for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; i--, j--) {
int c1 = i >= 0 ? a.charAt(i) - '0' : 0;
int c2 = j >= 0 ? b.charAt(j) - '0' : 0;
ans.append((c1 + c2 + carry) % 2);
carry = (c1 + c2 + carry) / 2;
}
ans.append(carry == 1 ? '1' : "");
return ans.reverse().toString();
}
}