forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
51 lines (36 loc) · 1.02 KB
/
AddBinary.java
File metadata and controls
51 lines (36 loc) · 1.02 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
package Algorithms.string;
public class AddBinary {
public String addBinary(String a, String b) {
if (a == null || b == null) {
return null;
}
if (a.length() == 0) {
return b;
}
if (b.length() == 0) {
return a;
}
StringBuilder sb = new StringBuilder();
int p1 = a.length() - 1;
int p2 = b.length() - 1;
int carry = 0;
while (p1 >= 0 || p2 >= 0) {
int sum = carry;
if (p1 >= 0) {
sum += (a.charAt(p1) - '0');
}
if (p2 >= 0) {
sum += (b.charAt(p2) - '0');
}
char c = sum % 2 == 1 ? '1': '0';
sb.insert(0, c);
carry = sum / 2;
p1--;
p2--;
}
if (carry == 1) {
sb.insert(0, '1');
}
return sb.toString();
}
}