--- title: 'LeetCode 445. Add Two Numbers II' disqus: hackmd --- # LeetCode 445. Add Two Numbers II ## Description You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. ## Example ![](https://i.imgur.com/eqhULfi.png) Input: l1 = [7,2,4,3], l2 = [5,6,4] Output: [7,8,0,7] ## Constraints * The number of nodes in each linked list is in the range [1, 100]. * 0 <= Node.val <= 9 * It is guaranteed that the list represents a number that does not have leading zeros. ## Answer 此題做法和第2題類似,一樣是將list中每位數解析出來相加並考慮進位項,比較不同的是list排列並沒有反過來,為了我們要從個位數開始計算,所以我們將list先做reverse後再開始相加,最後要接新空間時也是往前接,如此順序才會是正確的。 ```Cin= struct ListNode* my_rever_list(struct ListNode *head); struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ int add = 0; l1 = my_rever_list(l1); l2 = my_rever_list(l2); struct ListNode *ans = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *tmp = NULL; ans->next = NULL; while(l1 != NULL || l2 != NULL){ if(l1 != NULL && l2 != NULL){ ans->val = (l1->val + l2->val + add) % 10; add = (l1->val + l2->val + add) / 10; l1 = l1->next; l2 = l2->next; } else if(l1 != NULL){ ans->val = (l1->val + add) % 10; add = (l1->val + add) / 10; l1 = l1->next; } else{ ans->val = (l2->val + add) % 10; add = (l2->val + add) / 10; l2 = l2->next; } if(add || l1 != NULL || l2 != NULL){ tmp = (struct ListNode*)malloc(sizeof(struct ListNode)); tmp->next = ans; ans = tmp; } } if(add){ans->val = 1;} return ans; } struct ListNode* my_rever_list(struct ListNode *head){ struct ListNode *nxt = NULL, *cur = NULL; while(head != NULL){ nxt = head->next; head->next = cur; cur = head; head = nxt; } return cur; } ``` ## Link https://leetcode.com/problems/add-two-numbers-ii/ ###### tags: `Leetcode`