zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    CF948D Perfect Security
    bzoj 1015 [JSOI2008]星球大战starwar
    XJOI 7191 Genius ACM
    bzoj 1491 [NOI2007]社交网络
    CF1066F Yet another 2D Walking
    iOS main函数讲解
    iOS 邓白氏编码的申请
    iOS 开发与H5交互(JavaScriptCore框架的使用)
    iOS 开发之RunLoop
    iOS 蓝牙开发之(CoreBlueTooth)
  • 原文地址:https://www.cnblogs.com/wesson2019-blog/p/15499041.html
Copyright © 2011-2022 走看看