
难度:Medium
解题思路:一位一位加,记得处理最后的进位。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
/** * 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* res = new ListNode(-1); ListNode* cur = res; int carry = 0; while(l1 != NULL || l2 != NULL) { int n1 = l1==NULL?0:l1->val; int n2 = l2 == NULL ? 0 : l2->val; int sum = n1+n2+carry; carry = sum / 10; sum = sum % 10; ListNode *new_node = new ListNode(sum); cur->next = new_node; cur = new_node; if(l1 != NULL) l1 = l1->next; if(l2 != NULL) l2 = l2->next; } if(carry>0) { ListNode *new_node = new ListNode(carry); cur->next = new_node; } return res->next; } };
|
近期评论