## DEV Community 👩‍💻👨‍💻

FakeStandard

Posted on

### Problem statement

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"

### Solution

public string AddBinary(string a, string b)
{
var x = Convert.ToInt32(a, 2);
var y = Convert.ToInt32(b, 2);

var res = x + y;

return Convert.ToString(res, 2);
}

public string AddBinary(string a, string b)
{
// 將 a,b 補 0 直到相同長度
int maxLen = a.Length > b.Length ? a.Length : b.Length;
a = a.PadLeft(maxLen, '0');
b = b.PadLeft(maxLen, '0');

// true 表示進位, false 則無
bool carry = false;
StringBuilder sb = new StringBuilder();

maxLen--;

// 依據各種狀況進行相加
while (maxLen > -1)
{
add = a[maxLen] + b[maxLen];

if (add == 98) // a+b=2
{
if (carry)
sb.Insert(0, '1');
else
{
sb.Insert(0, '0');
carry = true;
}
}
else if (add == 97) // a+b=1
{
if (carry)
sb.Insert(0, '0');
else
sb.Insert(0, '1');
}
else // a+b=0
{
if (carry)
{
sb.Insert(0, '1');
carry = false;
}
else
sb.Insert(0, '0');
}

maxLen--;
}

if (carry) sb.Insert(0, '1');

return sb.ToString();
}

### Reference

LeetCode Solution

GitHub Repository

Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or click like on my Leetcode solution
or follow my GitHub
or buy me a coffee ⬇️ I'd appreciate it.