addTwoNumbers

算法第二题:

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.

my solution我的解法:

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
30
31
32
/**
* 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) {
ListNode returnListNode = new ListNode(0);
ListNode m1 = l1;
ListNode m2 = l2;
ListNode currentNode = returnListNode;
int nextVal =0;
while(m1 !=null || m2 !=null){
int x = (m1!=null)?m1.val:0;
int y = (m2!=null)?m2.val:0;
int sum = x+y+nextVal;
nextVal = sum/10;
currentNode.next = new ListNode(sum%10);
currentNode = currentNode.next;
if(m1 !=null) m1=m1.next;
if(m2 !=null) m2=m2.next;
}

if(nextVal>0){
currentNode.next = new ListNode(nextVal);
}
return returnListNode.next;
}
}

Runtime: 19 ms, faster than 99.14% of Java online submissions for Add Two Numbers.
Memory Usage: 47.7 MB, less than 47.01% of Java online submissions for Add Two Numbers.

Most Vote Solution投票最多的解法:

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
/**
* 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) {
int carry = 0;
ListNode p, dummy = new ListNode(0);
p = dummy;
while (l1 != null || l2 != null || carry != 0) {
if (l1 != null) {
carry += l1.val;
l1 = l1.next;
}
if (l2 != null) {
carry += l2.val;
l2 = l2.next;
}
p.next = new ListNode(carry%10);
carry /= 10;
p = p.next;
}
return dummy.next;
}
}

Runtime: 20 ms, faster than 80.39% of Java online submissions for Add Two Numbers.
Memory Usage: 48.4 MB, less than 6.94% of Java online submissions for Add Two Numbers.