67. Add Binary
class Solution {
public String addBinary(String a, String b) {
StringBuilder res = new StringBuilder();
int aIdx = a.length()-1;
int bIdx = b.length()-1;
int carry = 0;
while (aIdx >= 0 || bIdx >= 0) {
int aNum = aIdx >= 0 ? a.charAt(aIdx) - '0' : 0;
int bNum = bIdx >= 0 ? b.charAt(bIdx) - '0' : 0;
int sum = aNum + bNum + carry;
carry = sum/2;
res.append(sum%2);
aIdx--;
bIdx--;
}
if (carry == 1) {
res.append(1);
}
return res.reverse().toString();
}
}
Last updated