Leetcode 2 Add Two Numbers 题解分析

又 roll 到了一个以前做过的题,不过现在用 Java 也来写一下,是 easy 级别的,所以就简单说下

简要介绍

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 contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
就是给了两个链表,用来表示两个非负的整数,在链表中倒序放着,每个节点包含一位的数字,把他们加起来以后也按照原来的链表结构输出

样例

example 1

1
2
3
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

example 2

1
2
Input: l1 = [0], l2 = [0]
Output: [0]

example 3

1
2
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = new ListNode();
if (l1 == null && l2 == null) {
return root;
}
ListNode tail = root;
int entered = 0;
// 这个条件加了 entered,就是还有进位的数
while (l1 != null || l2 != null || entered != 0) {
int temp = entered;
if (l1 != null) {
temp += l1.val;
l1 = l1.next;
}
if (l2 != null) {
temp += l2.val;
l2 = l2.next;
}
entered = (temp - temp % 10) / 10;
tail.val = temp % 10;
// 循环内部的控制是为了排除最后的空节点
if (l1 != null || l2 != null || entered != 0) {
tail.next = new ListNode();
tail = tail.next;
}
}
// tail = null;
return root;
}

这里唯二需要注意的就是两个点,一个是循环条件需要包含进位值还存在的情况,还有一个是最后一个节点,如果是空的了,就不要在 new 一个出来了,写的比较挫