Last active
August 23, 2016 07:47
-
-
Save lyleaf/7701983a2600e701a2c3d3bf28d74f0e to your computer and use it in GitHub Desktop.
两个整数分别用两个Linked List 表示 ,把它们加起来
This file contains hidden or 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
class Solution { | |
public: | |
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { | |
int before = 0; | |
ListNode* res = new ListNode(0); | |
ListNode* pre = res; | |
while (l1 != NULL || l2 != NULL){ | |
int current = 0; | |
if (!l2) { current = l1->val; l1 = l1->next; } | |
else if (!l1) { current = l2->val; l2 = l2->next; } | |
else { | |
current = l1->val + l2->val; | |
l1 = l1->next; | |
l2 = l2->next; | |
} | |
current += before; | |
if (current > 9){ | |
current -= 10; | |
before = 1; | |
} | |
else before = 0; | |
pre->next = new ListNode(current); | |
pre = pre->next; | |
} | |
if (before != 0) pre->next = new ListNode(before); | |
return res->next; | |
} | |
}; |
This file contains hidden or 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) { | |
int before = 0; | |
ListNode* res = new ListNode(0); | |
ListNode* pre = res; | |
while (l1 || l2 || before){ | |
if (l1) { before += l1->val; l1 = l1->next; } | |
if (l2) { before += l2->val; l2 = l2->next; } | |
pre->next = new ListNode(before%10); | |
before /= 10; | |
pre = pre->next; | |
} | |
return res->next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
可以把进位放到while的判断中去。
求进位的时候可以用pre/10 pre%10来求。