LeetCode Solutions
2. Add Two Numbers
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode* curr = &dummy;
int carry = 0;
while (l1 || l2 || carry) {
if (l1 != nullptr) {
carry += l1->val;
l1 = l1->next;
}
if (l2 != nullptr) {
carry += l2->val;
l2 = l2->next;
}
curr->next = new ListNode(carry % 10);
carry /= 10;
curr = curr->next;
}
return dummy.next;
}
};
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
int carry = 0;
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;
}
curr.next = new ListNode(carry % 10);
carry /= 10;
curr = curr.next;
}
return dummy.next;
}
}
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
curr = dummy
carry = 0
while carry or l1 or l2:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
curr.next = ListNode(carry % 10)
carry //= 10
curr = curr.next
return dummy.next