Add Binary
EasyTop Interview 150 Bit ManipulationProblem
You are given two strings a and b made only of the characters
'0' and '1'. Each one is a binary number, with the most significant bit first.
Return their sum as a binary string. Do not convert the whole strings to integers: they may be far longer than any built-in number type can hold.
Constraints
- 1 ≤ a.length, b.length ≤ 10⁴
- a and b contain only '0' and '1'
- No leading zeros, except for the number 0 itself
Examples: pick one to animate
Solutions
Time: Every column is handled once, plus at most one extra column for a final carry.
Space: The answer needs one digit per column, and the digits are built before reversing them.
Walk from the right end of both strings at once. In each column, add the two digits (a missing digit counts as 0) and the carry. The digit to write is the total mod 2 and the new carry is the total divided by 2. Keep going while digits or a carry remain, then reverse the digits you wrote.