304 North Cardinal St.
Dorchester Center, MA 02124

# Add Binary LeetCode Solution

## Problem – Add Binary

Given two binary strings `a` and `b`, return their sum as a binary string.

Example 1:

``````Input: a = "11", b = "1"
Output: "100"``````

Example 2:

``````Input: a = "1010", b = "1011"
Output: "10101"``````

Constraints:

• `1 <= a.length, b.length <= 104`
• `a` and `b` consist only of `'0'` or `'1'` characters.
• Each string does not contain leading zeros except for the zero itself.

### Add Binary LeetCode Solution in Java

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

### Add Binary LeetCode Solution in C++

``````class Solution
{
public:
string addBinary(string a, string b)
{
string s = "";

int c = 0, i = a.size() - 1, j = b.size() - 1;
while(i >= 0 || j >= 0 || c == 1)
{
c += i >= 0 ? a[i --] - '0' : 0;
c += j >= 0 ? b[j --] - '0' : 0;
s = char(c % 2 + '0') + s;
c /= 2;
}

return s;
}
};
``````

### Add Binary LeetCode Solution in Python

``````class Solution:
def addBinary(self, a: str, b: str) -> str:
carry = 0
result = ''

a = list(a)
b = list(b)

while a or b or carry:
if a:
carry += int(a.pop())
if b:
carry += int(b.pop())

result += str(carry %2)
carry //= 2

return result[::-1]
``````
##### Add Binary LeetCode Solution Review:

In our experience, we suggest you solve this Add Binary LeetCode Solution Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Add Binary LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Add Binary LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions