-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd Two Numbers
28 lines (28 loc) Β· 906 Bytes
/
Add Two Numbers
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
string a, b;
ListNode *result = nullptr;
while(l1) { a.push_back(l1->val+'0'); l1 = l1->next;}
while(l2) { b.push_back(l2->val+'0'); l2 = l2->next;}
int l = a.size()-1, r = b.size()-1, carry = 0;
while(l >= 0 || r >= 0 || carry == 1) {
int c = (l >= 0 ? a[l--]-'0' : 0) + ( r >= 0 ? b[r--]-'0' : 0) + carry;
ListNode *temp = new ListNode(c%10);
temp->next = result;
result = temp;
carry = c/10;
}
return result;
}
};