LeetCode 67: Add Binary Solution

Master LeetCode problem 67 (Add Binary), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can iterate through the two input strings from right to left, perform binary addition, and keep track of the carry. We start by initializing an empty result string and variables to store the current index of each input string, the sum of the current bits, and the carry. We add the corresponding bits from both strings along with the carry, update the result string, and calculate the new carry. Finally, we handle any remaining carry if present.

Algorithm:

  1. Initialize variables i and j to the length of strings a and b minus one respectively, and carry to 0.
  2. Initialize an empty string result to store the sum.
  3. Loop while i >= 0, j >= 0, or carry > 0.
    • Calculate the sum of bits at indices i and j.
    • Update the result string and carry based on the sum.
    • Decrement i and j.
  4. Reverse the result string and return it.

Time Complexity: O(max(N, M)), where N and M are the lengths of input strings a and b.

Space Complexity: O(max(N, M)), for the space used by the result string.

Solution Code

class Solution {
    public String addBinary(String a, String b) {
        int i = a.length() - 1, j = b.length() - 1, carry = 0;
        StringBuilder result = new StringBuilder();
        
        while (i >= 0 || j >= 0 || carry > 0) {
            int sum = carry;
            if (i >= 0) sum += a.charAt(i--) - '0';
            if (j >= 0) sum += b.charAt(j--) - '0';
            
            result.append(sum % 2);
            carry = sum / 2;
        }
        
        return result.reverse().toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 67 (Add Binary)?

This page provides optimized solutions for LeetCode problem 67 (Add Binary) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 67 (Add Binary)?

The time complexity for LeetCode 67 (Add Binary) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 67 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 67 in Java, C++, or Python.

Back to LeetCode Solutions