"Accepted" C# solution


  • 0
    E

    This is my C# solution. I didn't see one in the list, so I add mine. It's not the finest code.

     public string AddBinary(string i, string j) {
           if (String.IsNullOrEmpty(i) && String.IsNullOrEmpty(j))
                    return String.Empty;
    
                var result = new int[Math.Max(i.Length, j.Length) + 1];
    
                var carryOne = 0;
    
                int index = Math.Max(i.Length, j.Length);
                var iIndex = i.Length - 1;
                var jIndex = j.Length - 1;
                while (index >= 0)
                {
                    int iVal = 0;
                    int jVal = 0;
    
                    if (iIndex < i.Length && iIndex >= 0)
                    {
                        iVal = i[iIndex] - '0';
                    }
                    if (jIndex < j.Length && jIndex >= 0)
                    {
                        jVal = j[jIndex] - '0';
                    }
    
                    var val = iVal + jVal + carryOne;
    
                    result[index] = val & 1;
                    carryOne = val > 1 ? 1 : 0;
                    index--;
                    jIndex--;
                    iIndex--;
                }
    
                var resultStr = String.Join("", result);
                return resultStr.StartsWith("0") ? resultStr.Substring(1) : resultStr;
            }
    

Log in to reply
 

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