Esempio n. 1
0
        private static Node SumForward(Node n1, Node n2)
        {
            if (n1 == null || n2 == null)
            {
                return(null);
            }

            // Length n1, n2
            var length1 = n1.Length();
            var length2 = n2.Length();

            n1 = PadZeroToLeft(n1, length2 - length1);
            n2 = PadZeroToLeft(n2, length1 - length2);

            var  sum        = new PartialSum();
            var  partialSum = RecAdd(sum, n1, n2);
            Node resultHead = partialSum.Sum;

            if (partialSum.Carry > 0)
            {
                // Insert before
                var newHead = new Node(partialSum.Carry);
                newHead.Next = resultHead;
                resultHead   = newHead;
            }

            return(resultHead);
        }
Esempio n. 2
0
        private static PartialSum RecAdd(PartialSum sum, Node n, Node m)
        {
            if (n == null && m == null)
            {
                return(sum);
            }

            var sum2 = RecAdd(sum, n.Next, m.Next);

            var val     = n.Value + m.Value + sum2.Carry;
            var newNode = new Node(val % 10);

            newNode.Next = sum2.Sum;
            sum2.Sum     = newNode;
            sum2.Carry   = val / 10;
            return(sum2);
        }