Leetcode 445. Add Two Numbers II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Add Two Numbers II

2. 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 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) {
stack<int> s1, s2;
ListNode* current = l1;
while(current) {
s1.push(current->val);
current = current->next;
}
current = l2;
while(current) {
s2.push(current->val);
current = current->next;
}
int carry = 0;
int sum = 0;
ListNode* pre = nullptr;
while(!s1.empty() || !s2.empty()) {
sum = 0;
if(!s1.empty()) {
sum += s1.top();
s1.pop();
}
if(!s2.empty()) {
sum += s2.top();
s2.pop();
}
sum += carry;
carry = sum>9?1:0;
current = new ListNode(sum % 10);
current->next = pre;
pre = current;
}
if(carry) {
current = new ListNode(1);
current->next = pre;
}
return current;
}
};

Reference

  1. https://leetcode.com/problems/add-two-numbers-ii/description/
如果有收获,可以请我喝杯咖啡!