Given two binary strings a and b, return their sum as a binary string.
https://leetcode.com/problems/add-binary/description/
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
class Solution {
public String addBinary(String a, String b) {
StringBuilder res = new StringBuilder();
int i = a.length()-1;
int j = b.length()-1;
boolean carry=false;
while(i>-1||j>-1){
char aC = (i>-1)?a.charAt(i--):'0';
char bC = (j>-1)?b.charAt(j--):'0';
if(aC=='1'&&bC=='1'){
res = (carry) ? res.append('1') : res.append('0');
carry = true;
}else if(aC=='0'&&bC=='0'){
res = (carry)?res.append('1'):res.append('0');
carry = false;
}else{
res = (carry)?res.append('0'):res.append('1');
}
}
if(carry) res.append('1');
return res.reverse().toString();
}
}