首页 > 代码库 > leetcode67

leetcode67

public class Solution {
    public string AddBinary(string a, string b) {
        var list = new List<string>();

            if (a.Length > b.Length)
            {
                //补充b的长度
                var dif = a.Length - b.Length;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < dif; i++)
                {
                    sb.Append("0");
                }
                b = sb.ToString() + b;

                var len = a.Length;
                var jin = 0;
                for (int i = len - 1; i >= 0; i--)
                {
                    var ca = Convert.ToInt32(a[i].ToString());
                    var cb = Convert.ToInt32(b[i].ToString());
                    var cur = ca + cb + jin;
                    if (cur >= 2)
                    {
                        jin = 1;
                    }
                    else
                    {
                        jin = 0;
                    }
                    cur = cur % 2;
                    list.Add(cur.ToString());
                }
                if (jin == 1)
                {
                    list.Add("1");
                }
            }
            else
            {
                var dif = b.Length - a.Length;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < dif; i++)
                {
                    sb.Append("0");
                }
                a = sb.ToString() + a;

                var len = b.Length;
                var jin = 0;
                for (int i = len - 1; i >= 0; i--)
                {
                    var ca = Convert.ToInt32(a[i].ToString());
                    var cb = Convert.ToInt32(b[i].ToString());
                    var cur = ca + cb + jin;
                    if (cur >= 2)
                    {
                        jin = 1;
                    }
                    else
                    {
                        jin = 0;
                    }
                    cur = cur % 2;
                    list.Add(cur.ToString());
                }
                if (jin == 1)
                {
                    list.Add("1");
                }
            }

            StringBuilder sbx = new StringBuilder();
            for (int i = list.Count - 1; i >= 0; i--)
            {
                sbx.Append(list[i]);
            }
            return sbx.ToString();
    }
}

https://leetcode.com/problems/add-binary/#/description

leetcode67