Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 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.
completion:
class Solution {
public String addBinary(String a, String b) {
String min_bin;
String max_bin;
StringBuilder s = new StringBuilder();
if (a.length() >= b.length()) {
min_bin = b;
max_bin = a;
} else {
min_bin = a;
max_bin = b;
}
int[] number = new int[max_bin.length() + 1];
int carry = 0;
for (int i = 1; i <= max_bin.length(); i++) {
int z;
if (min_bin.length() - i >= 0) {
int x = min_bin.charAt(min_bin.length() - i) - '0';
int y = max_bin.charAt(max_bin.length() - i) - '0';
z = x + y + carry;
} else {
int x = max_bin.charAt(max_bin.length() - i) - '0';
z = x + carry;
}
s.insert(0, z % 2);
carry = z / 2;
}
if (carry == 1) {
s.insert(0, carry);
}
return s.toString();
}
}