067. Add Binary
At a Glance
- Topic: Bit Manipulation
- Pattern: Math / Simulation
- Difficulty: Easy
- LeetCode: 067
Problem Statement
Given two binary strings a and b, return their sum as a binary string.
Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.Approach & Solution Steps
Iterate through the strings from right to left, simulating binary addition. Keep track of the carry and append the sum modulo 2 to the result string.
Optimal JS Solution
function addBinary(a, b) {
let result = "";
let carry = 0;
let i = a.length - 1, j = b.length - 1;
while (i >= 0 || j >= 0 || carry > 0) {
const sum = (i >= 0 ? Number(a[i--]) : 0) + (j >= 0 ? Number(b[j--]) : 0) + carry;
result = (sum % 2) + result;
carry = Math.floor(sum / 2);
}
return result;
}Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?