Created
September 2, 2018 03:02
-
-
Save zhangxiaomu01/6e28ce2d0741f10e1f04138d4f470871 to your computer and use it in GitHub Desktop.
This is the solution for add two numbers problem in Leetcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 preHead(0), *p = &preHead; | |
int extra = 0; | |
while (l1 || l2 || extra) { | |
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra; | |
extra = sum / 10; | |
p->next = new ListNode(sum % 10); | |
p = p->next; | |
l1 = l1 ? l1->next : l1; | |
l2 = l2 ? l2->next : l2; | |
} | |
return preHead.next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment