067.Add Binary

Test cases

1
2
3
4
5
6
7
8
9
10
"1"
"1"
"0"
"0"
"0"
"1010101"
"1100011"
"10101101010"
"10011"
"11011"

Solution 1: accepted 3ms 81%

The performance is good, but the style is a diseaster man.

Time: O(n)
Space: O(n)

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
public String addBinary(String a, String b) {
int la = a.length();
int lb = b.length();
int common = la < lb? la : lb;
boolean carry = false;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < common; i++ ) {
char ca = a.charAt(la - i - 1);
char cb = b.charAt(lb - i - 1);
if (ca != cb) { // 1 and 0
if(carry) {
sb.insert(0, "0"); // keep carrying on
} else {
sb.insert(0, "1");
}
} else if (ca == '1') { // 1 and 1
if(carry) {
sb.insert(0, "1"); // keep carrying on
} else {
sb.insert(0, "0");
carry = true;
}
} else { // 0 and 0
if(carry) {
sb.insert(0, "1");
carry = false;
} else {
sb.insert(0, "0");
}
}
}
String longer = la < lb? b : a;
for (int j = longer.length() - common - 1; j >= 0; j--) {
if (longer.charAt(j) == '1') {
if (carry) {
sb.insert(0, "0"); // keep carrying on
} else {
sb.insert(0, "1");
}
} else {
if (carry) {
sb.insert(0, "1");
carry = false;
} else {
sb.insert(0, "0");
}
}
}
if (carry) {
sb.insert(0, "1");
}
return sb.toString();
}

Solution 2: accepted 6ms

Looks better, but worse performance than solution 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public String addBinary(String a, String b) {
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0)
sum += Character.getNumericValue(a.charAt(i--));
if (j >= 0)
sum += Character.getNumericValue(b.charAt(j--));
sb.insert(0, Integer.toString(sum % 2));
carry = sum >= 2? 1 : 0;
}
if (carry > 0)
sb.insert(0, "1");
return sb.toString();
}

Further improvement: 4ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public String addBinary(String a, String b) {
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0)
sum += a.charAt(i--) - '0'; // get numeric value: ('9' = 57)-('0' = 48) = 9, worth 2ms
if (j >= 0)
sum += b.charAt(j--) - '0';
sb.insert(0, Integer.toString(sum % 2));
carry = sum >= 2? 1 : 0;
}
if (carry > 0)
sb.insert(0, "1");
return sb.toString();
}