2017-09-07 LeetCode_002 Add Two Numbers
2017-09-07 15:38
337 查看
2. Add Two Numbers
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution:
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
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution:
/**
2
* Definition for singly-linked list.
3
* struct ListNode {
4
* int val;
5
* ListNode *next;
6
* ListNode(int x) : val(x), next(NULL) {}
7
* };
8
*/
9
class Solution {
10
public:
11
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
12
ListNode *l3 = new ListNode(l1->val+l2->val), *p = l3;
13
l1 = l1->next; l2 = l2->next;
14
for (; l1 != NULL || l2 != NULL; l1 = (l1 == NULL ? NULL : l1->next), l2 = (l2 == NULL ? NULL : l2->next)) {
15
int a = 0, b = 0;
16
if (l1 != NULL) a = l1->val;
17
if (l2 != NULL) b = l2->val;
18
p->next = new ListNode(a+b+p->val/10);
19
p->val %= 10;
20
p = p->next;
21
}
22
if (p->val >= 10) {
23
p->next = new ListNode(p->val/10);
24
p->val %= 10;
25
}
26
return l3;
27
}
28
};
相关文章推荐
- LeetCode 002 Add Two Numbers
- Leetcode_002_Add_Two_Numbers
- leetcode解题方案--002--AddTwoNumbers
- 【leetcode】002 Add Two Numbers
- 【LeetCode002-003算法/编程练习C++】---Add Two Numbers||寻找最长无重复字母子串。//第三题之后有空要再想一想…
- LeetCode002__Add Two Numbers
- leetcode 002 Add_Two_Numbers
- LeetCode 002 AddTwoNumbers
- LeetCode 002 Add Two Numbers
- leetcode002:Add Two Numbers
- Add Two Numbers - leetcode002
- LeetCode-Add Two Numbers_002
- 002_LeetCode_2 Add Two Numbers 题解
- LeetCode 002-Add Two Numbers
- 002 Add Two Numbers [Leetcode]
- LeetCode002 Add Two Numbers
- 【LeetCode-面试算法经典-Java实现】【002-Add Two Numbers (单链表表示的两个数相加)】
- [LeetCode]题解(python):002-Add Two Numbers
- 002 Add Two Numbers [Leetcode]
- LeetCode-002 Add Two Numbers