# 67. Add Binary

### Description

Given two binary strings, return their sum (also a binary string).

The input strings are both **non-empty** and contains only characters `1` or `0`.

### Constraints

* Each string consists only of `'0'` or `'1'` characters.
* `1 <= a.length, b.length <= 10^4`
* Each string is either `"0"` or doesn't contain any leading zero.

### **Approach**

### Links

* [GeeksforGeeks](https://www.geeksforgeeks.org/program-to-add-two-binary-strings)
* [Leetcode](https://leetcode.com/problems/add-binary)
* ProgramCreek

### Examples

{% tabs %}
{% tab title="Example 1" %}
**Input:** a = "11", b = "1"&#x20;

**Output:** "100"
{% endtab %}

{% tab title="Example 2" %}
**Input:** a = "1010", b = "1011"

**Output:** "10101"
{% endtab %}
{% endtabs %}

### Solutions

{% tabs %}
{% tab title="Solution 1" %}

```java
/**
 * 
 * 
 */

class Solution {
    public String addBinary(String a, String b) {
        int alen = a.length();
        int blen = b.length();
        int sum = 0;
        StringBuilder result = new StringBuilder("");
        while(alen > 0 || blen > 0) {
            if(alen > 0 && a.charAt(--alen) == '1') {
                sum++;
            }
            if(blen > 0 && b.charAt(--blen) == '1') {
                sum++;
            }
            result.insert(0, (sum%2));
            sum /= 2;
        }
        if(sum == 1) {
            result.insert(0, "1");
        }
        return result.toString();
    }
}
```

{% endtab %}

{% tab title="Solution 2" %}

```java
/**
 * 
 * 
 */

class Solution {
    public String addBinary(String a, String b) {
        int alen = a.length();
        int blen = b.length();
        int sum = 0;
        StringBuilder result = new StringBuilder("");
        while(alen > 0 || blen > 0) {
            sum += (alen > 0)? a.charAt(--alen)-'0': 0;
            sum += (blen > 0)? b.charAt(--blen)-'0': 0;
            result.append(sum&1);
            sum /= 2;
        }
        if(sum == 1) {
            result.append(1);
        }
        return result.reverse().toString();
    }
}
```

{% endtab %}
{% endtabs %}

### **Follow up**

*


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://code-snippets.hbamithkumara.com/leetcode/problems/1-100/add-binary.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
