Given two binary strings, the task is to add them and return their sum as another binary string. The addition is performed from right to left while maintaining a carry, similar to normal binary addition.
- Each position is processed using the two binary digits and the carry from the previous position.
- The result is built in reverse order and then reversed to obtain the final binary string.
Example:
Input: a = "11", b = "1"
Output: "100"Explanation:
11
+ 1
-----
100Starting from the rightmost digit:
- 1 + 1 = 0, carry 1
- 1 + 0 + 1 = 0, carry 1
- Remaining carry 1 is added to the result
Therefore, the sum is "100".
Approach
The idea is to traverse both strings from right to left and add their corresponding digits along with the carry.
- Start from the last character of both strings.
- Add the two binary digits and the current carry.
- Store sum % 2 as the current result digit.
- Update the carry as sum / 2.
- Move to the next pair of digits from right to left.
- If one string is shorter, treat its missing digits as 0.
- After processing all digits, add the remaining carry if it exists.
- Reverse the result to obtain the correct order.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string addBinary(string a, string b)
{
int i = a.size() - 1;
int j = b.size() - 1;
int carry = 0;
string result;
while (i >= 0 || j >= 0 || carry) {
int sum = carry;
if (i >= 0)
sum += a[i--] - '0';
if (j >= 0)
sum += b[j--] - '0';
result.push_back((sum % 2) + '0');
carry = sum / 2;
}
reverse(result.begin(), result.end());
return result;
}
int main()
{
string a = "1101";
string b = "100";
cout << addBinary(a, b) << '\n';
return 0;
}
Output
10001
Explanation
For the input strings "1101" and "100", the addition is performed from right to left:
1101
+ 0100
------
10001
The shorter string is not explicitly padded with zeroes. Instead, when its index becomes invalid, the corresponding digit is simply treated as 0. For each position:
- sum stores the two digits and the previous carry.
- sum % 2 gives the current binary digit.
- sum / 2 gives the carry for the next position.
- Since digits are processed from right to left, the result is reversed before returning.