Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int m = a.length()-1, n = b.length()-1;
int carry = 0;
while(m >= 0 || n >= 0) {
int v1 = m<0?0:a.charAt(m--)-'0';
int v2 = n<0?0:b.charAt(n--)-'0';
int sum = v1+v2+carry;
sb.append(sum%2);
carry = sum/2;
}
if(carry!=0)
sb.append(carry);
return sb.reverse().toString();
}