Tutorialspoint
Problem
Solution
Submissions

Binary Strings

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

Write a C program to add two binary strings. Given two binary strings a and b, return their sum as a binary string. A binary string consists of only '0' and '1' characters.

Example 1
  • Input: a = "11", b = "1"
  • Output: "100"
  • Explanation:
    • Step 1: Convert binary string "11" to decimal: 1*2^1 + 1*2^0 = 2 + 1 = 3
    • Step 2: Convert binary string "1" to decimal: 1*2^0 = 1
    • Step 3: Add the two decimal numbers: 3 + 1 = 4
    • Step 4: Convert decimal 4 to binary: 100
    • Step 5: Therefore, the binary sum is "100"
Example 2
  • Input: a = "1010", b = "1011"
  • Output: "10101"
  • Explanation:
    • Step 1: Convert binary string "1010" to decimal: 1*2^3 + 0*2^2 + 1*2^1 + 0*2^0 = 8 + 0 + 2 + 0 = 10
    • Step 2: Convert binary string "1011" to decimal: 1*2^3 + 0*2^2 + 1*2^1 + 1*2^0 = 8 + 0 + 2 + 1 = 11
    • Step 3: Add the two decimal numbers: 10 + 11 = 21
    • Step 4: Convert decimal 21 to binary: 10101
    • Step 5: Therefore, the binary sum is "10101"
Constraints
  • 1 ≤ a.length, b.length ≤ 10^4
  • a and b consist only of '0' or '1' characters
  • Each string does not contain leading zeros except for the zero itself
  • Time Complexity: O(max(len(a), len(b)))
  • Space Complexity: O(max(len(a), len(b)))
StringsSnowflakePhillips
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

  • Don't convert to decimal and back - work directly with binary
  • Process the strings from right to left (least significant bit first)
  • Keep track of carry when adding bits
  • Remember that 1 + 1 in binary is 0 with a carry of 1
  • Handle cases where the strings have different lengths
  • Build the result string in reverse and then reverse it at the end

Steps to solve by this approach:

 Step 1: Get the length of both binary strings
 Step 2: Determine the maximum length to allocate enough space for the result
 Step 3: Process the strings from right to left, treating each character as a binary digit
 Step 4: Add corresponding digits along with any carry from previous addition
 Step 5: Calculate the new carry (sum / 2) and the current digit (sum % 2)
 Step 6: Build the result string in reverse order
 Step 7: Return the result string, adjusting the pointer to skip any leading zeros

Submitted Code :