ArrayOfDigit - lyubo24/CSharp-2 GitHub Wiki

using System; using System.Collections.Generic;

namespace ArrayOfDigit { class Program { static void Main(string[] args) { //Write a method that adds two positive integer numbers represented as arrays of digits (each array element arr[i] contains a digit; the last digit is kept in arr[0]). //Each of the numbers that will be added could have up to 10 000 digits.

        List<byte> firstNumber = new List<byte> { 1, 9, 7, 5, 9 };
        List<byte> secondNumber = new List<byte> { 1, 2 };

        //List<byte> firstNumber = new List<byte> { 1, 2, 3, 4 };
        //List<byte> secondNumber = new List<byte> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        FixTheEmptyPosition(firstNumber, secondNumber);
        SumDigit(firstNumber, secondNumber);

    }

    static void SumDigit(List<byte> a, List<byte> b)
    {
        List<byte> newList = new List<byte>();
        int length = a.Count;

        byte add = 0;  // Остатък от събирането 
        for (int i = 0; i < length; i++)
        {
            if ((byte)(a[i] + b[i] + add) < 10)
            {
                byte temp = (byte)(a[i] + b[i] + add);
                newList.Add(temp);
                add = 0;
            }
            else
            {
                int temp = (byte)((a[i] + b[i] + add) % 10);  // temp = 13 % 10;  -> 3
                add = (byte)((a[i] + b[i] + add) / 10);       // add = 13 / 10;   -> 1
                newList.Add((byte)temp);
            }
        }
        // Ако все още  имам остатък 1 го добавям в началото на List-та
        if (add == 1)
        {
            newList.Add(1);
        }

        newList.Reverse();  // Обръщам масиваза да изведа верният резултат -> 5, 4, 3, 2, 1   ->  1, 2, 3, 4, 5
        Console.WriteLine(string.Join("", newList));
    }
    //Проверявам дължината на масивите и допълвам по-късият масив с нули за да станат еднакви
    private static void FixTheEmptyPosition(List<byte> a, List<byte> b)
    {
        int lengthMin = Math.Min(a.Count, b.Count);
        int lengthMax = Math.Max(a.Count, b.Count);
        a.Reverse();  //Обръщам масивите за да мога да ги събера по-лесно в последствие -> 1, 2, 3 -> 3, 2, 1
        b.Reverse();  //Обръщам масивите за да мога да ги събера по-лесно в последствие -> 1, 2, 3, 4, 5, 6 -> 6, 5, 4, 3, 2, 1

        for (int i = lengthMin; i < lengthMax; i++)
        {
            if (a.Count < b.Count)
            {
                a.Add(0);   // 0, 0, 0, 3, 2, 1
            }
            else
            {
                b.Add(0);
            }
        }
    }
}

}

⚠️ **GitHub.com Fallback** ⚠️