# 【LeetCode】 2. Add Two Numbers ## Description > 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. > 給你兩個非空的linked list 代表兩個非負整數。每個位數用相反的順序存在節點裡面。 > 請將兩數相加後,一樣回傳一個linked list。 > 你可以假設裡面不會有任何多餘的零。 ## Example: ``` Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. ``` ## Solution * 用大數加法的概念去做即可。 * 從個位數開始兩數相加,如果加完大於9就進位(自己-10,下一位+1)。 * 一直做直到兩個數都加完且不用進位了。 ### Code ```C++=1 //Definition for singly-linked list. //struct ListNode { // int val; // ListNode *next; // ListNode(int x) : val(x), next(NULL) {} //}; class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *ans = NULL; for(bool plusOne = false,ListNode* last = NULL;!(l1==NULL&&l2==NULL)||plusOne;) { ListNode *n = new ListNode((int)plusOne); if(l1!=NULL) { n->val += l1->val; l1=l1->next; } if(l2!=NULL) { n->val += l2->val; l2=l2->next; } if(n->val > 9) { n->val -=10; plusOne = true; } else plusOne = false; if(last == NULL) { last = n; ans = n; } else { last->next = n; last = last->next; } } return ans; } }; ``` ###### tags: `LeetCode` `C++`