# My java solution

• ``````public static String addBinary(String a, String b) {

String sum = getSum(a, b);
int length = sum.length();
int start = 0;
if (isZero(sum)) {
return "0";
}
while (sum.charAt(start) == '0') {
start++;
}
return new String(sum.substring(start, length));

}

public static String getSum(String a, String b) {
if (a == null || a.isEmpty() || isZero(a)) {
return b;
}

if (b == null || b.isEmpty() || isZero(b)) {
return a;
}

char[] charA = a.toCharArray();
char[] charB = b.toCharArray();
int lengthA = charA.length;
int lengthB = charB.length;
String sum = "";
String carr = "";
int ia = lengthA - 1, ib = lengthB - 1;
while (ia >= 0 && ib >= 0) {
sum += charA[ia] == charB[ib] ? "0" : "1";
if (charA[ia] != charB[ib] || charA[ia] == '0') {
carr += "0";
} else {
carr += "1";
}
ia--;
ib--;
}

while (ia >= 0) {
carr += "0";
sum += charA[ia];
ia--;
}

while (ib >= 0) {
carr += "0";
sum += charB[ib];
ib--;
}

sum = reverse(sum);
carr = reverse(carr);
carr += "0";
if (!isZero(carr)) {
sum = getSum(sum, carr);
}

return sum;

}

private static boolean isZero(String carr) {
if (carr == null || carr.length() == 0) {
return true;
}
return !carr.contains("1");
}

private static String reverse(String s) {
if (s == null || s.length() <= 1) {
return s;
}

int high = s.length() - 1;
int low = 0;
char[] charArray = s.toCharArray();
for (; low < high; low++, high--) {
char tmp = charArray[low];
charArray[low] = charArray[high];
charArray[high] = tmp;
}
return new String(charArray);

}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.