Add Binary
Schoolbook binary addition with carry — walk both strings from the right.
4 min read
math string bit-manipulation
Problem#
Add two binary strings and return the binary sum as a string.
Examples#
"11", "1"→"100"."1010", "1011"→"10101".
Constraints#
1 <= a.length, b.length <= 10^4.
Approach#
Two pointers from the right with carry. Append (sum % 2) to result; carry is sum / 2. Reverse at the end.
Solution#
class Solution {public: string addBinary(string a, string b) { int i = a.size() - 1, j = b.size() - 1, carry = 0; string out; while (i >= 0 || j >= 0 || carry) { int x = (i >= 0) ? a[i--] - '0' : 0; int y = (j >= 0) ? b[j--] - '0' : 0; int s = x + y + carry; out.push_back('0' + s % 2); carry = s / 2; } reverse(out.begin(), out.end()); return out; }};func addBinary(a string, b string) string { i, j, carry := len(a)-1, len(b)-1, 0 out := []byte{} for i >= 0 || j >= 0 || carry > 0 { x, y := 0, 0 if i >= 0 { x = int(a[i] - '0') i-- } if j >= 0 { y = int(b[j] - '0') j-- } s := x + y + carry out = append(out, byte('0'+s%2)) carry = s / 2 } for l, r := 0, len(out)-1; l < r; l, r = l+1, r-1 { out[l], out[r] = out[r], out[l] } return string(out)}class Solution: def addBinary(self, a: str, b: str) -> str: i, j, carry = len(a) - 1, len(b) - 1, 0 out: list[str] = [] while i >= 0 or j >= 0 or carry: x = int(a[i]) if i >= 0 else 0 y = int(b[j]) if j >= 0 else 0 s = x + y + carry out.append(str(s % 2)) carry = s // 2 i -= 1 j -= 1 return ''.join(reversed(out))var addBinary = function(a, b) { let i = a.length - 1, j = b.length - 1, carry = 0; const out = []; while (i >= 0 || j >= 0 || carry) { const x = i >= 0 ? a.charCodeAt(i--) - 48 : 0; const y = j >= 0 ? b.charCodeAt(j--) - 48 : 0; const s = x + y + carry; out.push(String(s % 2)); carry = Math.floor(s / 2); } 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 out = new StringBuilder(); while (i >= 0 || j >= 0 || carry > 0) { int x = i >= 0 ? a.charAt(i--) - '0' : 0; int y = j >= 0 ? b.charAt(j--) - '0' : 0; int s = x + y + carry; out.append((char) ('0' + s % 2)); carry = s / 2; } return out.reverse().toString(); }}function addBinary(a: string, b: string): string { let i = a.length - 1, j = b.length - 1, carry = 0; const out: string[] = []; while (i >= 0 || j >= 0 || carry) { const x = i >= 0 ? a.charCodeAt(i--) - 48 : 0; const y = j >= 0 ? b.charCodeAt(j--) - 48 : 0; const s = x + y + carry; out.push(String(s % 2)); carry = Math.floor(s / 2); } return out.reverse().join('');}Editorial#
Identical structure to decimal addition, but with base 2. Each digit’s sum is at most 3 (1+1+1), producing digit 1 and carry 1 — the loop condition handles arbitrary trailing carry.
Complexity#
- Time:
O(max(m, n)). - Space:
O(max(m, n)).
Concept revision#
Related#