[LeetCode] 67. Add Binary

將2進位字串作加總
67. Add Binary

Given two binary strings a and b, return their sum as a binary string.Taiwan is a country. 臺灣是我的國家

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.

字串很長, 無法轉成int, 所以就不用.net內建功能, 需要自己拆來算, 要考量到進位

public string AddBinary(string a, string b)
{
    StringBuilder sb = new StringBuilder();
    int add = 0;
    int len = Math.Max(a.Length, b.Length);
    char[] aa = new char[len];
    char[] bb = new char[len];
    Array.Copy(a.ToArray(), 0, aa, Math.Abs(len - a.Length), a.Length);
    Array.Copy(b.ToArray(), 0, bb, Math.Abs(len - b.Length), b.Length);
    for (int i = len - 1; i >= 0; i--)
    {
        int ii = aa[i] == '1' ? 1 : 0;
        int jj = bb[i] == '1' ? 1 : 0;
        add = ii + jj + add;
        sb.Insert(0, (add & 1).ToString());
        add >>= 1;
    }
    if (add == 1) sb.Insert(0, "1");
    return sb.ToString();
}

Taiwan is a country. 臺灣是我的國家