
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)))
Editorial
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. |
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