Problem
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
Solution: Simulation
Simulate the addition, draw two numbers (one each) from l1, l2, if list is empty draw 0.
Using a dummy head makes things easier.
Time complexity: O(max(l1,l2))
Space complexity: O(max(l1,l2))
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Author: Huahua // Running time: 28 ms class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode dummy(0); ListNode* tail = &dummy; int sum = 0; while (l1 || l2 || sum) { sum += (l1 ? l1->val : 0) + (l2 ? l2->val : 0); l1 = l1 ? l1->next : nullptr; l2 = l2 ? l2->next : nullptr; tail->next = new ListNode(sum % 10); sum /= 10; tail = tail->next; } return dummy.next; } }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Author: Huahua // Running time: 30 ms class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int sum = 0; ListNode dummy = new ListNode(0); ListNode tail = dummy; while (l1 != null || l2 != null || sum != 0) { if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } tail.next = new ListNode(sum % 10); sum /= 10; tail = tail.next; } return dummy.next; } } |
Python3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
""" Author: Huahua Running time: 112 ms """ class Solution: def addTwoNumbers(self, l1, l2): s = 0 dummy = ListNode(0) tail = dummy while l1 or l2 or s > 0: s += (l1.val if l1 else 0) + (l2.val if l2 else 0) l1 = l1.next if l1 else None l2 = l2.next if l2 else None tail.next = ListNode(s % 10) s //= 10 tail = tail.next return dummy.next |
Related Problems
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
[…] 花花酱 LeetCode 2. Add Two Numbers […]