Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
public class Solution {
public String addBinary(String a, String b) {
if (a.length() < b.length()) return addBinary(b,a);
int i=1, carry = 0, aLen = a.length(), bLen = b.length();
char[] result = a.toCharArray();
while (i <= aLen) {
carry += (a.charAt(aLen-i) == '1') ? 1 : 0;
carry += (i <= bLen && b.charAt(bLen-i) == '1') ? 1 : 0;
result[aLen-i] = (char) ((carry & 1) + '0');
carry = carry >> 1;
i++;
}
return carry == 1 ? "1" + new String(result) : new String(result);
}
}