Tutorialspoint
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))
StringsAccenturePwC
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 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

Steps to solve by this approach:

 Step 1: Initialize a StringBuilder to store the result and set a carry variable to 0.

 Step 2: Start from the rightmost bits (least significant) of both strings.
 Step 3: Calculate the sum of the current bits from both strings and the carry from the previous addition.
 Step 4: Append the result bit (sum % 2) to the result string.
 Step 5: Update the carry as sum / 2 for the next iteration.
 Step 6: After processing all bits, if there's a carry left, append it to the result string.
 Step 7: Reverse the result string as we built it from right to left.

Submitted Code :