LeetCode 2. Add Two Numbers

正好复习一下链表

Question

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse orderand 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.

Code provided:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

}
}

Solution

source: leetcode

En

Before starting summing up two lists, create a new linked list to store the summed up value. Given and , starting with the head of and . Each digit is in the range of , so it is possible that summing two digits may result in a value that is greater than 9, therefore require digits to represent. Hence, extra digit is needed during each iteration to carry the overflowing value.


CN

代码中已经提供了,因此所需要的步骤就是创建一个新的空的linked list。从头开始迭代,并将相加的数值存入到新的linked list之中。值得注意的事情就是,每个数字的区间是,因此,当两位数字相加的时候就可能会出现十位数的可能,也就因此需要额外的变量保存十位数的数字。


Code

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
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(sum % 10);
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;
}

Python3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def addTwoNumbers(self, l1, l2):
dummy = cur = ListNode(0)
carry = 0
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
cur.next = ListNode(carry%10)
cur = cur.next
# floor division
# 10 / 4 => 2.5
# 10 // 4 = 2
carry //= 10
return dummy.next

Complexity Analysis

  • Time Complexity:

  • Space Complexity:

Reference

Python solution - 80ms - Easy to read

Solution

-------The end of this article  Thank you for your reading-------
0%