Skip to content

Instantly share code, notes, and snippets.

@lyleaf
Last active August 23, 2016 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyleaf/7701983a2600e701a2c3d3bf28d74f0e to your computer and use it in GitHub Desktop.
Save lyleaf/7701983a2600e701a2c3d3bf28d74f0e to your computer and use it in GitHub Desktop.
两个整数分别用两个Linked List 表示 ,把它们加起来
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;
}
};
/**
* 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;
}
};
@lyleaf
Copy link
Author

lyleaf commented Aug 23, 2016

可以把进位放到while的判断中去。
求进位的时候可以用pre/10 pre%10来求。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment