• 【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;
  • 相关阅读:
    OpenMP并行编程
    visual studio 2005 编fortran程序,运行后dos窗口显示问题
    在fortran下进行openmp并行计算编程
    Intel Visual Fortran Compiler 11调用lapack库实现并行多处理计算
    C#数组的排序
    [转载]:Endnote 自定义style文件的默认位置
    正则表达式语法
    EFDC主控文件efdc.inp文件的xml格式化处理——转载http://blog.sina.com.cn/s/articlelist_1584892573_0_1.html
    Delphi 的绘图功能[1]
    根据点集合画曲线(贝塞尔)
  • 原文地址:https://www.cnblogs.com/hero4china/p/5938438.html
Copyright © 2020-2023  润新知