# Super short Java code

• ``````public class Solution {
public String addBinary(String a, String b) {
StringBuilder sum = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry == 1) {
int digitA = i < 0 ? 0 : a.charAt(i--) - '0';
int digitB = j < 0 ? 0 : b.charAt(j--) - '0';
sum.insert(0, (digitA + digitB + carry) % 2);
carry = (digitA + digitB + carry) / 2;
}
return sum.toString();
}
}``````

• there is no leading zeros. digitA and digitB and carry can not be equal to 0 at the same time.

• what if a = 000001 , b = 0000000001 - I assumed that the answer should have minimum possible digits (ie, 10), but that may not be a requirement.

• the input does not have leading zero, therefore output does not neither.

• I agree that if the input doesn't have leading zeros, the output will not. But no where in the question is it explicitly mentioned that the input will not have leading zeros. At least personally in an interview situation, I will not make that assumption.

• If that is the case, then mowhere is mentioned that the output must contain no leading zero. It is not fair that you assume input may have leading zero while output must not.

• No, this is super short :p

``````String addBinary(String a, String b) {
return new BigInteger(a, 2).add(new BigInteger(b, 2)).toString(2);
}
``````

• So why do you add - '0' in the last of digitA and digitB?

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