67. Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
public class Solution {
public String addBinary(String a, String b) {
if (a==null) return b;
if (b==null) return a;
StringBuilder sb= new StringBuilder();
int alen= a.length()-1, blen= b.length()-1, carry=0;
while (alen>=0 || blen>=0 || carry==1){
int anum= alen>=0 ? a.charAt(alen--)-'0' : 0;
int bnum= blen>=0 ? b.charAt(blen--)-'0' : 0;
int res= anum ^ bnum ^ carry;
carry= anum+bnum+carry>=2 ? 1 : 0;
sb.append(res);
}
return sb.reverse().toString();
}
}