Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
normalize two string to be the same length, then add each char.
public String addBinary(String a, String b) {
if (a==null||b==null||a.isEmpty()||b.isEmpty()) {
return "";
}
if (a.length()<b.length()) {
return addBinary(b,a);
}
int diff = a.length()-b.length();
for (int i=diff; i>0; i--) {
b = '0' + b;
}
int index = a.length()-1;
StringBuilder sb = new StringBuilder();
int carryOn = 0;
while (index>=0) {
int sum = (a.charAt(index)-'0') + (b.charAt(index)-'0') + carryOn;
if (sum>=2) {
carryOn = 1;
} else {
carryOn = 0;
}
sb.insert(0, sum%2);
index = index-1;
}
if (carryOn>0) {
sb.insert(0,'1');
}
return sb.toString();
}