• 【leedcode】add-two-numbers


    You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
    
    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    两数之和(考察链表操作):

    链表长度不一,有进位情况,最后的进位需要新增节点。

    int up = 0;
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1 == null) {
                return l2;
            }
            if (l2 == null) {
                return l1;
            }
            ListNode newList = new ListNode(-1);
            ListNode newNode, rootList = newList;
            while (l1 != null && l2 != null) {
                newNode = new ListNode(l1.val + l2.val + up);
                up = newNode.val /10;
                newNode.val = mod(newNode.val,10, up);
                newList.next = newNode;
                newList = newList.next;
                l1 = l1.next;
                l2 = l2.next;
            }
            newList = loopList(l1, newList);
            newList = loopList(l2, newList);
            if (up > 0) {
                newList.next = new ListNode(up);
            }
            return rootList.next;
        }
        
        ListNode loopList(ListNode loopList, ListNode newList) {
            ListNode newNode;
            while (loopList != null) {
                newNode = new ListNode(loopList.val + up);
                up = newNode.val /10;
                newNode.val = mod(newNode.val, 10, up);
                newList.next = newNode;
                newList = newList.next;
                loopList = loopList.next;
            }
            return newList;
        }
        static int mod(int x, int y, int v) {
             return x - y * v;
        }

    码出来的代码不不如答案,哎,超级简洁:

    ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(mod(sum , 10 , carry));
            curr = curr.next;
            if (p != null) p = p.next;
            if (q != null) q = q.next;
        }
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
  • 相关阅读:
    GNU Linux中的SO_RCVLOWAT和SO_SNDLOWAT说明
    Spring.NET 的IOC(依赖注入)
    c# post 数据的方法
    C# .NET中的 反射的应用
    C# .NET修改注册表
    DataTabel DataSet 对象 转换成json
    sqlserver 行转列
    asp.net 二级域名session共享
    Asp.Net集群中Session共享
    微软企业库DBBA的研究
  • 原文地址:https://www.cnblogs.com/hero4china/p/5938438.html
Copyright © 2020-2023  润新知