Add Two Binary Strings
Problem
Given two non-negative integers a and b as binary strings, return their sum as a binary string. Don't convert via integer types — pretend you only have characters.
Input
a = "1010", b = "1011"Output
"10101"Walk both strings from the right. Each step adds two bits plus a carry; the column digit is the parity, the new carry is 1 iff the column sum ≥ 2.
def add_binary(a, b):
i, j, carry = len(a) - 1, len(b) - 1, 0
out = []
while i >= 0 or j >= 0 or carry:
s = carry
if i >= 0: s += int(a[i]); i -= 1
if j >= 0: s += int(b[j]); j -= 1
out.append(str(s & 1))
carry = s >> 1
return ''.join(reversed(out))
function addBinary(a, b) {
let i = a.length - 1, j = b.length - 1, carry = 0;
const out = [];
while (i >= 0 || j >= 0 || carry) {
let s = carry;
if (i >= 0) s += a.charCodeAt(i--) - 48;
if (j >= 0) s += b.charCodeAt(j--) - 48;
out.push(s & 1);
carry = s >> 1;
}
return out.reverse().join("");
}
class Solution {
public String addBinary(String a, String b) {
int i = a.length() - 1, j = b.length() - 1, carry = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0 || carry > 0) {
int s = carry;
if (i >= 0) s += a.charAt(i--) - '0';
if (j >= 0) s += b.charAt(j--) - '0';
sb.append(s & 1);
carry = s >> 1;
}
return sb.reverse().toString();
}
}
string addBinary(string a, string b) {
int i = (int) a.size() - 1, j = (int) b.size() - 1, carry = 0;
string out;
while (i >= 0 || j >= 0 || carry) {
int s = carry;
if (i >= 0) s += a[i--] - '0';
if (j >= 0) s += b[j--] - '0';
out.push_back('0' + (s & 1));
carry = s >> 1;
}
reverse(out.begin(), out.end());
return out;
}