2. Add Two Numbers
你可以假設這兩個數不包含任何前導零,除了數字 0 本身。
範例:
輸入: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] 輸出: [8,9,9,9,0,0,0,1]
Python
# Definition for singly-linked list.class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next
class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ dummy = ListNode(0) current = dummy carry = 0
while l1 or l2 or carry: val1 = (l1.val if l1 else 0) val2 = (l2.val if l2 else 0) total = val1 + val2 + carry
carry = total // 10 current.next = ListNode(total % 10) current = current.next
if l1: l1 = l1.next if l2: l2 = l2.next
return dummy.next
11.64MB, 51ms
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
current = dummy
carry = 0
while l1 or l2 or carry:
val1 = (l1.val if l1 else 0)
val2 = (l2.val if l2 else 0)
total = val1 + val2 + carry
carry = total // 10
current.next = ListNode(total % 10)
current = current.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
return dummy.next
11.64MB, 51ms
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode(0);
ListNode* current = dummy;
int carry = 0;
while (l1 != nullptr || l2 != nullptr || carry != 0) {
int val1 = (l1 != nullptr) ? l1->val : 0;
int val2 = (l2 != nullptr) ? l2->val : 0;
int sum = val1 + val2 + carry;
carry = sum / 10;
current->next = new ListNode(sum % 10);
current = current->next;
if (l1 != nullptr) l1 = l1->next;
if (l2 != nullptr) l2 = l2->next;
}
return dummy->next;
}
};
76.12MB, 26ms
Javascript
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val);
* this.next = (next===undefined ? null : next);
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let dummy = new ListNode(0);
let current = dummy;
let carry = 0;
while (l1 !== null || l2 !== null || carry !== 0) {
let val1 = (l1 !== null) ? l1.val : 0;
let val2 = (l2 !== null) ? l2.val : 0;
let sum = val1 + val2 + carry;
carry = Math.floor(sum / 10);
current.next = new ListNode(sum % 10);
current = current.next;
if (l1 !== null) l1 = l1.next;
if (l2 !== null) l2 = l2.next;
}
return dummy.next;
};
55.37MB, 104ms