2. Add Two Numbers

大正数相加。通过两个逆序的链表相加实现

private void BigIntAdd(string num1, string num2)
{
    SLinkedList<int> slist1 = new SLinkedList<int>();
    foreach (var item in num1)
    {
        slist1.Insert(CharUnicodeInfo.GetDecimalDigitValue(item));
    }
    SLinkedList<int> slist2 = new SLinkedList<int>();
    foreach (var item in num2)
    {
        slist2.Insert(CharUnicodeInfo.GetDecimalDigitValue(item));
    }
    Console.WriteLine($"Input :({slist1.Head.Print()}) + ({slist2.Head.Print()})");
    var rslt = AddTwoNumbers(slist1.Head, slist2.Head);
    Console.WriteLine($"Output:{rslt.Print()}");
}

/// <summary>
/// 2个逆序的链表,从低位开始相加,得出结果也逆序输出,返回值是逆序结果链表的头结点。
/// </summary>
/// <param name="node1"></param>
/// <param name="node2"></param>
/// <returns></returns>
public SLinkedListNode<int> AddTwoNumbers(SLinkedListNode<int> node1, SLinkedListNode<int> node2)
{
    if (node1 == null || node2 == null)
    {
        return null;
    }
    SLinkedListNode<int> head = new SLinkedListNode<int>();
    var cur = head;
    int carry = 0;
    while (node1 != null || node2 != null)
    {
        int x, y;
        if (node1 == null)
        {
            x = 0;
        }
        else
        {
            x = node1.Data;
        }
        if (node2 == null)
        {
            y = 0;
        }
        else
        {
            y = node2.Data;
        }
        cur.Next = new SLinkedListNode<int>((x + y + carry) % 10);
        cur = cur.Next;
        carry = (x + y + carry) / 10;
        if (node1 != null)
        {
            node1 = node1.Next;
        }
        if (node2 != null)
        {
            node2 = node2.Next;
        }
    }
    if (carry > 0)
    {
        cur.Next = new SLinkedListNode<int>(carry % 10);
    }
    return head.Next;
}
posted @ 2021-11-02 15:03  wesson2019  阅读(22)  评论(0编辑  收藏  举报