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 && b == null ) return null;
if(a == null || b == null) return a == null ? b :a;
StringBuilder sb = new StringBuilder();
int p = a.length() - 1;
int q = b.length() - 1;
int carry = 0;
while(p >=0 || q >=0){
int i1 = p >= 0 ? a.charAt(p--) - '0' : 0;
int i2 = q >= 0 ? b.charAt(q--) - '0' : 0;
sb.append((i1+i2+carry)%2);
carry = (i1+i2+carry)/2;
}
if(carry != 0){
sb.append(carry);
}
return sb.reverse().toString();
}
}
simpler code
public class Solution {
public String addBinary(String a, String b) {
int carry = 0;
int al = a.length()-1, bl = b.length()-1;
StringBuilder sb = new StringBuilder();
while(al >=0 || bl>=0 || carry > 0){
int x = al >= 0 ? a.charAt(al--) - '0' : 0;
int y = bl >= 0 ? b.charAt(bl--) - '0' : 0;
sb.append((x+y+carry)%2);
carry = (x+y+carry)/2;
}
return sb.reverse().toString();
}
}