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) {
int m = a.length();
int n = b.length();
String res = "";
int carry = 0;
int i = 0;
while(i<m || i<n || carry!=0){
int x = (i<m) ? a.charAt(m - 1 - i) - '0' : 0;
int y = (i<n) ? b.charAt(n - 1 - i) - '0' : 0;
res = (x + y + carry)%2 + res;
carry = (x + y + carry)/2;
i++;
}
return res;
}
}