Add Binary - Problem

Given two binary strings a and b, return their sum as a binary string.

A binary string contains only characters '0' and '1'. You need to perform binary addition following the same rules as decimal addition, but in base 2.

Binary Addition Rules:

  • 0 + 0 = 0
  • 0 + 1 = 1
  • 1 + 0 = 1
  • 1 + 1 = 10 (0 with carry 1)

Input & Output

Example 1 — Basic Addition
$ Input: a = "11", b = "1"
Output: "100"
💡 Note: Binary addition: 11₂ + 1₂ = 100₂ (which is 3 + 1 = 4 in decimal)
Example 2 — Different Lengths
$ Input: a = "1010", b = "1011"
Output: "10101"
💡 Note: Binary addition: 1010₂ + 1011₂ = 10101₂ (which is 10 + 11 = 21 in decimal)
Example 3 — Single Digit
$ Input: a = "1", b = "1"
Output: "10"
💡 Note: Binary addition: 1₂ + 1₂ = 10₂ (which is 1 + 1 = 2 in decimal)

Constraints

  • 1 ≤ a.length, b.length ≤ 104
  • a and b consist only of '0' or '1' characters
  • Each string does not contain leading zeros except for the zero itself

Visualization

Tap to expand
Add Binary - Bit-by-Bit Addition with Carry INPUT Binary String a: 1 1 "11" Binary String b: 1 "1" Binary Addition Setup: 1 1 + 1 ? ? ? Process right to left like decimal addition ALGORITHM STEPS 1 Initialize Pointers i=len(a)-1, j=len(b)-1 carry=0, result="" 2 Add Bits + Carry sum = a[i] + b[j] + carry 1 + 1 + 0 = 2 3 Compute Result Bit bit = sum % 2 = 0 carry = sum / 2 = 1 4 Continue Until Done Move pointers left Handle remaining carry Iteration Table i j sum bit carry 1 0 2 0 1 0 - 2 0 1 - - 1 1 0 FINAL RESULT Output Binary String: 1 0 0 "100" Verification: a = "11" = 3 (decimal) b = "1" = 1 (decimal) 3 + 1 = 4 "100" = 4 (decimal) OK Result verified! Key Insight: Binary addition follows the same principle as decimal addition: process digits from right to left, keeping track of carry. In binary: 0+0=0, 0+1=1, 1+1=10 (0 with carry 1), 1+1+1=11 (1 with carry 1). Time: O(max(n,m)) | Space: O(max(n,m)) for the result string. TutorialsPoint - Add Binary | Bit-by-Bit Addition with Carry Approach
Asked in
Facebook 15 Google 12 Amazon 8
89.6K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen