Question
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
1
2
3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
My Solution
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
class {
public :
ListNode* addTwoNumbers (ListNode *l1, ListNode *l2) {
ListNode* res = new ListNode(0 );
ListNode* l1node = l1;
ListNode* l2node = l2;
ListNode* end = res;
int carry = 0 ;
int num = 0 ;
while (l1node != NULL || l2node != NULL ){
int x = (l1node != NULL ) ? l1node->val : 0 ;
int y = (l2node != NULL ) ? l2node->val : 0 ;
int sum = x+y+carry;
carry = (x+y+carry)/10 ;
end->next = new ListNode(sum%10 );
end = end->next;
l1node = (l1node != NULL ) ? l1node->next : l1node;
l2node = (l2node != NULL ) ? l2node->next : l2node;
}
if (carry != 0 ){
end->next = new ListNode(carry);
}
return res->next;
}
};
time: 58ms
Sample 22ms submission
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
static const auto _____ = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = new ListNode(0);
ListNode *tail = head;
int carry = 0;
while(l1 || l2 || carry){
int n = (l1?l1->val:0) + (l2?l2->val:0) + carry;
tail -> next = new ListNode(n % 10);
carry = n / 10;
tail = tail -> next;
l1 = l1?l1 -> next:NULL;
l2 = l2?l2 -> next:NULL;
}
return head -> next;
}
};
no much difference in main thought, only some difference in implementation.
近期评论