Given two binary strings a and b, return their sum as a binary string.
The inputs can be far longer than any built-in integer type, so converting to a number and back is not a viable strategy.
We use analytics and advertising cookies to understand how the site is used and whether our ads on Facebook and Instagram work. They are set only if you accept. See our Privacy Policy for details.
Given two binary strings a and b, return their sum as a binary string.
The inputs can be far longer than any built-in integer type, so converting to a number and back is not a viable strategy.
An easy strings problem, graded against 6 test cases (3 of them hidden).
Parsing, comparison, and character-frequency reasoning.
Reach for it when you see: String input where the work is scanning, comparing, or counting characters.
More Strings problems →The framing matters: with inputs up to 10^4 digits, no integer type can hold these values, so parsing to a number is not an option. (This is why the problem exists - the one-liner using big integers sidesteps the exercise entirely.)
So add digit by digit from the right, carrying. At each position, `sum = digitA + digitB + carry`; the emitted digit is `sum % 2` and the new carry is `sum / 2` (which in binary is just "was the sum at least 2").
The loop condition is the part that gets fumbled. It must continue while either string has digits remaining or the carry is non-zero - treating a missing digit as 0. Stopping when the shorter string runs out truncates the answer, and stopping before flushing the carry turns `"11" + "1"` into `"00"` instead of `"100"`.
Building the result back-to-front means appending to an array and reversing at the end, rather than prepending to a string - prepending is O(n) per operation and makes the whole thing quadratic.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
These apply to the pattern as a whole, not just this problem.