LeetCode 67. Add Binary

Question

Given two binary strings a and b, return their sum as a binary string.

Example 1:

1
2
Input: a = "11", b = "1"
Output: "100"

Example 2:

1
2
Input: a = "1010", b = "1011"
Output: "10101"

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

Source: https://leetcode.com/problems/add-binary/

Solution

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
public String addBinary(String a, String b) {
if (a == null && b == null) {
return "";
} else if (a == null) {
return b;
} else if (b == null) {
return a;
}
int lenA = a.length();
int lenB = b.length();
if (lenA == 0 && lenB == 0) {
return "";
} else if (lenA == 0) {
return b;
} else if (lenB == 0) {
return a;
}

StringBuilder sb = new StringBuilder();
int ia = lenA - 1, ib = lenB - 1;
int carry = 0;
while (ia >= 0 && ib >= 0) {
int bitA = a.charAt(ia) - '0';
int bitB = b.charAt(ib) - '0';
int bitC = (bitA + bitB + carry) % 2;
carry = (bitA + bitB + carry) / 2;
sb.append(bitC);
ia--;
ib--;
}
// these two loops handle remaining bits
// only one loop will be entered
while (ia >= 0) {
int bitA = a.charAt(ia) - '0';
int bitC = (bitA + carry) % 2;
carry = (bitA + carry) / 2;
sb.append(bitC);
ia--;
}
while (ib >= 0) {
int bitB = b.charAt(ib) - '0';
int bitC = (bitB + carry) % 2;
carry = (bitB + carry) / 2;
sb.append(bitC);
ib--;
}
// if carry is the most significant bit
if (carry == 1) {
sb.append(carry);
}

sb.reverse();
return sb.toString();
}
Author

Weihao Ye

Posted on

2022-05-20

Updated on

2022-05-20

Licensed under