Tutorialspoint
Problem
Solution
Submissions

Add Binary Strings

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to add two binary strings and return their sum as a binary string. The input strings contain only characters '0' and '1', and you need to perform binary addition with proper carry handling.

Example 1
  • Input: a = "11", b = "1"
  • Output: "100"
  • Explanation:
    • Binary string a is "11" (decimal 3).
    • Binary string b is "1" (decimal 1).
    • Adding 3 + 1 = 4 in decimal. 4 in binary is "100".
    • Therefore, "11" + "1" = "100".
Example 2
  • Input: a = "1010", b = "1011"
  • Output: "10101"
  • Explanation:
    • Binary string a is "1010" (decimal 10).
    • string b is "1011" (decimal 11).
    • Adding from right to left with carry.
    • 0+1=1, 1+1=10(carry 1), 0+0+1=1, 1+1=10(carry 1).
    • Final result with carry is "10101".
Constraints
  • 1 ≤ a.length, b.length ≤ 10^4
  • Each string consists only of '0' and '1' characters
  • Each string does not contain leading zeros except for the zero itself
  • Time Complexity: O(max(m,n)) where m and n are lengths of strings
  • Space Complexity: O(max(m,n))
StringsHCL TechnologiesApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Process strings from right to left (least significant bit first)
  • Keep track of carry value during addition
  • Handle cases where strings have different lengths
  • Continue processing until both strings are exhausted and no carry remains
  • Build result string and reverse it at the end

Steps to solve by this approach:

 Step 1: Initialize result string, carry variable, and pointers for both strings.
 Step 2: Start processing from the rightmost digits of both strings.
 Step 3: In each iteration, calculate sum of current digits plus carry.
 Step 4: Extract the current digit (sum % 2) and prepend to result string.
 Step 5: Update carry value (sum / 2) for the next position.
 Step 6: Continue until both strings are fully processed and no carry remains.
 Step 7: Return the final result string containing the binary sum.

Submitted Code :