Algo. Add strings

https://leetcode.com/problems/add-strings/

       public string AddStrings(string num1, string num2)
        {
            var needZeroes = num1.Length - num2.Length;

            // adding leading zeroes
            var absNeedZeroes = Math.Abs(needZeroes);
            if (needZeroes > 0)
                num2 = DoAddLeadingZeros(absNeedZeroes, num2);
            else
                num1 = DoAddLeadingZeros(absNeedZeroes, num1);

            // adding manually

            var inMemory = 0;
            var sb = new StringBuilder();
            for (var i = num1.Length - 1; i >= 0; i--)
            {
                var sum = Int32.Parse(num1[i].ToString()) + Int32.Parse(num2[i].ToString()) + inMemory;
                var sumStr = sum.ToString();
                if (sum > 9)
                {
                    sb.Append(sumStr[1]); // for ex. from 12 we take 2
                    inMemory = 1;
                }
                else
                {
                    sb.Append(sumStr[0]);
                    inMemory = 0;
                }
            }

            if (inMemory == 1) sb.Append("1");

            return ReverseString(sb.ToString());
        }

        string ReverseString(string s)
        {
            var a = s.ToCharArray();
            Array.Reverse(a);
            return new string(a);
        }
    
        string DoAddLeadingZeros(int needZeros, string num)
        {
            StringBuilder sb = new StringBuilder();
            for (var i = 0; i < needZeros; i++)
                sb.Append("0");

            sb.Append(num);

            return sb.ToString();
        }    
This entry was posted in Без рубрики. Bookmark the permalink.