Practice › Strings
Add Two Binary Strings
Easy · Strings · Asked at Meta, Amazon, Microsoft, TCS, Infosys
Two non-negative numbers are given in binary (no leading zeros, except the number 0 itself). Print their sum in binary.
Input
Two lines: the binary strings a and b.
Output
The sum in binary.
Constraints
- 1 ≤ |a|, |b| ≤ 10^4
Add from the right with a carry, exactly like decimal addition: digit = (x + y + carry) % 2, carry = (x + y + carry) / 2. Do not convert to an integer — the numbers have up to 10^4 bits.
Example 1
Input
11 1
Output
100
Example 2
Input
1010 1011
Output
10101
Hints
- Add from the rightmost bit, carrying like in decimal addition.
- When one string runs out, treat its missing bits as 0.
- Do not forget a final carry.
Approach
Walk i and j from the ends of a and b. Each step: sum = carry + (bit of a or 0) + (bit of b or 0); append sum % 2 and set carry = sum / 2. Continue while either string has bits or carry is 1, then reverse the collected bits. Strings of 10^4 bits are far beyond any built-in integer type.
Complexity: O(|a| + |b|) time · O(|a| + |b|) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string a, b, res;
cin >> a >> b;
int i = a.size() - 1, j = b.size() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry) {
int sum = carry;
if (i >= 0) sum += a[i--] - '0';
if (j >= 0) sum += b[j--] - '0';
res += char('0' + sum % 2);
carry = sum / 2;
}
reverse(res.begin(), res.end());
cout << res << "\n";
return 0;
}Python solution
import sys
a, b = sys.stdin.read().split()[:2]
i, j, carry = len(a) - 1, len(b) - 1, 0
res = []
while i >= 0 or j >= 0 or carry:
s = carry
if i >= 0:
s += ord(a[i]) - 48
i -= 1
if j >= 0:
s += ord(b[j]) - 48
j -= 1
res.append(str(s % 2))
carry = s // 2
print("".join(reversed(res)))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String a = br.readLine().trim(), b = br.readLine().trim();
StringBuilder res = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int sum = carry;
if (i >= 0) sum += a.charAt(i--) - '0';
if (j >= 0) sum += b.charAt(j--) - '0';
res.append(sum % 2);
carry = sum / 2;
}
System.out.println(res.reverse());
}
}