Leetcode 2. Add Two Numbers

Posted DCREN

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 2. Add Two Numbers相关的知识,希望对你有一定的参考价值。

题目链接

https://leetcode.com/problems/add-two-numbers/description/

题目描述

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:


Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题解

依次遍历两个链表,计算对应位的和,如果有进位,计算进位。

XBB Time:刚开始写的check函数是把当前节点的前一个节点(记为pre),带进函数里面的,但是总是过不了,感觉是复制了一份传入,函数内的修改了值,但是外层函数中的pre并没有变,这就又回到了到底是值传递还是引用传递,其实是把引用复制了一份,然后传递进去,操作的是同一个内存地址,对该内存地址的修改是可见的,但是函数里的pre已经指向其他的地址了,外层函数的pre是不会变的。

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    int count = 0;
    ListNode start = new ListNode(0);
    ListNode pre = start;
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        while (l1 != null && l2 != null) {
            int val = l1.val + l2.val + count;
            count = val / 10;
            ListNode node = new ListNode(val % 10);
            pre.next = node;
            pre = node;
            l1 = l1.next;
            l2 = l2.next;
        }
        // check(l1, pre);
        // check(l2, pre);
        check(l1);
        check(l2);
        if (count != 0) {
            ListNode node = new ListNode(count);
            pre.next = node;
            pre = node;
        }
        return start.next;
    }
    
    /**
    * 开始把count带入了函数,有的用例过不了,count是值传递
    **/
    public void check(ListNode l) {
        while (l != null) {
            if (count == 0) {
                pre.next = l;
                break;
            }
            int val = l.val + count;
            count = val / 10;
            ListNode node = new ListNode(val % 10);
            pre.next = node;
            pre = node;
            l = l.next;
        }
    }
}

以上是关于Leetcode 2. Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章

2. 两个数相加 [leetcode 2: Add Two Numbers]

2. 两个数相加 [leetcode 2: Add Two Numbers]

LeetCode - 2 - Add Two Numbers

[leetcode][2] Add Two Numbers

[LeetCode]2. Add Two Numbers

LeetCode - 2. Add Two Numbers