LeetCode第二题:Add Two Numbers

时间:2023-03-09 08:15:25
LeetCode第二题:Add Two Numbers

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.

给出两个表示两个非负整数的非空链表。整数以相反的顺序存储,它们的每个节点都包含一个数字。将两个数字相加,并将其作为链接列表返回。

你可以假设这两个数字不包含任何前导零,除了第0个数字本身。

Example

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

题目本身不难,但是一定要记得最后的进位问题。下面贴下我的代码,代码量偏多,但是我认为比较好理解。

  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = new ListNode(0);
ListNode cur = root;//小技巧定义结果的上一个节点,返回时返回root.next
int temp = 0; //避免要先进行一次初值的计算
while (l1 != null || l2 != null) {
int n1 = 0;
int n2 = 0;
if (l1 != null) {//因为两个数不一定一样长,当一个数为空时,
n1 = l1.val; //用0计算即可,熟练的同学完全可以用三目运算符解决。
l1 = l1.next;
}
if (l2 != null) {
n2 = l2.val;
l2 = l2.next;
}
ListNode node = new ListNode((n1 + n2 + temp) % 10);
temp = (n1 + n2 + temp) / 10;
cur.next = node;
cur = node;
}
//这段代码千万不要忘记,如果最后有进位,需要添加节点。
//当然简洁的代码是在while循环中while (l1 != null || l2 != null||temp!=0)
//在循环中解决这个问题,我单独列出来,希望大家牢记这一点,如果在面试中漏掉这种情况
//应该会在面试官那里减分的。
if (temp != 0) {
cur.next = new ListNode(temp);
}
return root.next;
}