
Problem
Solution
Submissions
Binary Strings
Certification: Basic Level
Accuracy: 100%
Submissions: 1
Points: 5
Write a Java program to add two binary strings. The input strings represent binary numbers, and the output should be their sum in binary format. For example, given "11" and "1", the output should be "100".
Example 1
- Input: a = "11", b = "1"
- Output: "100"
- Explanation:
- Convert "11" to decimal: 3
- Convert "1" to decimal: 1
- Sum: 3 + 1 = 4
- Convert 4 to binary: "100"
- Therefore, the output is "100".
Example 2
- Input: a = "1010", b = "1011"
- Output: "10101"
- Explanation:
- Convert "1010" to decimal: 10
- Convert "1011" to decimal: 11
- Sum: 10 + 11 = 21
- Convert 21 to binary: "10101"
- Therefore, the output 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(a.length, b.length))
- Space Complexity: O(max(a.length, b.length))
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
- Process the two strings from right to left (least significant bit to most significant bit)
- Keep track of the carry
- Perform binary addition: 0+0=0, 0+1=1, 1+0=1, 1+1=0 with carry=1
- Append the result bit to the result string
- Don't forget to append the final carry if it's 1