public class Solution {
public String addBinary(String a, String b) {
StringBuffer sum = new StringBuffer();
int carry = 0;
for(int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; i = i >= 0 ? i - 1: i, j = j >= 0 ? j - 1: j) {
int digit = carry;
if(i >= 0) {
digit += a.charAt(i) - '0';
}
if(j >= 0) {
digit += b.charAt(j) - '0';
}
carry = digit / 2;
digit %= 2;
sum.insert(0, digit);
}
if(carry == 1) {
sum.insert(0, "1");
}
return sum.toString();
}
}
Time: O(max(m, n))
Space: O(1)