zoukankan      html  css  js  c++  java
  • 【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;
  • 相关阅读:
    字段名删不掉
    刷新f5/ctrl+f5
    大量数据模拟
    sub_query join drupal7 view_query_alter
    测试风格的代码
    csv/excel乱码
    window.location.reload(true)的异步现象
    扫描条形码
    yield %%% generator
    batch example
  • 原文地址:https://www.cnblogs.com/hero4china/p/5938438.html
Copyright © 2011-2022 走看看