C# code 21 lines


  • 0
    A

    21 lines, simple solution

    public string AddBinary(string a, string b) {
            if (string.IsNullOrEmpty(a)) return b;
            if (string.IsNullOrEmpty(b)) return a;
            var carrier = 0;
            var longer = a.Length >= b.Length ? a : b;
            var shorter = a.Length < b.Length ? a : b;
            var diff = longer.Length - shorter.Length;
            var arr = new char[longer.Length];
            for (var i = shorter.Length - 1; i >= 0; i--)
            {
                var temp = (longer[i + diff] + shorter[i] - 48 - 48 + carrier);
                arr[diff + i] = (char)(temp % 2 + 48);
                carrier = temp/2;
            }
            for (var i = diff - 1; i >= 0; i --)
            {
                var temp = (longer[i] + carrier - 48);
                arr[i] = (char) (temp%2 + 48);
                carrier = temp/2;
            }
            var r = new string(arr);
            return carrier > 0 ? "1" + r : r;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.