Add Binary
Add Binary
Math
Problem Statement
Given two binary strings a
and b
, return their sum as a binary string.
Example
Example 1:
Input: a = "11", b = "1"
Output: "100"
Solution (Math)
We can simulate binary addition from right to left, keeping track of a carry.
Algorithm Steps
- Initialize an empty result string and a carry of 0.
- Iterate from the end of both strings.
- In each step, add the digits from both strings (if they exist) and the carry.
- The new digit for the result is the sum modulo 2.
- The new carry is the sum divided by 2.
- Prepend the new digit to the result string.
- After the loop, if there's a remaining carry, prepend it to the result.
A
1010
B
1011
Carry
0
Result
Start with a = 1010, b = 1011, carry = 0.
Add Binary Solution