8000 Add Two Numbers · snowshawn/LeetCode@7e48f72 · GitHub
[go: up one dir, main page]

Skip to content

Commit 7e48f72

Browse files
committed
Add Two Numbers
1 parent 2f70df4 commit 7e48f72

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# 题目
2+
3+
给定两个非空链表,结点元素为非负整数,这些数字从小到大排列。将对应结点的两个数字相加,并返回一个新链表。
4+
5+
假设两个链表不以0打头。
6+
7+
**举例:**
8+
9+
``` stylus
10+
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
11+
Output: 7 -> 0 -> 8
12+
```
13+
14+
# 思路
15+
16+
对应位置元素相加,注意进位即可。使用divmod函数进行计算即可,很简单。
17+
18+
# 代码
19+
20+
**Python:**
21+
22+
``` python
23+
# Definition for singly-linked list.
24+
# class ListNode(object):
25+
# def __init__(self, x):
26+
# self.val = x
27+
# self.next = None
28+
29+
class Solution(object):
30+
def addTwoNumbers(self, l1, l2):
31+
"""
32+
:type l1: ListNode
33+
:type l2: ListNode
34+
:rtype: ListNode
35+
"""
36+
extra = 0
37+
root = n = ListNode(0)
38+
while l1 or l2 or extra:
39+
v1 = v2 = 0
40+
if l1:
41+
v1 = l1.val
42+
l1 = l1.next
43+
if l2:
44+
v2 = l2.val
45+
l2 = l2.next
46+
extra, val = divmod(v1 + v2 + extra, 10)
47+
n.next = ListNode(val)
48+
n = n.next
49+
return root.next
50+
```
51+
52+
**C++:**
53+
54+
``` cpp
55+
/**
56+
* Definition for singly-linked list.
57+
* struct ListNode {
58+
* int val;
59+
* ListNode *next;
60+
* ListNode(int x) : val(x), next(NULL) {}
61+
* };
62+
*/
63+
class Solution {
64+
public:
65+
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
66+
ListNode preHead(0), *p = &preHead;
67+
int extra = 0;
68+
while (l1 || l2 || extra) {
69+
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
70+
extra = sum / 10;
71+
p->next = new ListNode(sum % 10);
72+
p = p->next;
73+
l1 = l1 ? l1->next : l1;
74+
l2 = l2 ? l2->next : l2;
75+
}
76+
return preHead.next;
77+
}
78+
};
79+
```
80+
81+

0 commit comments

Comments
 (0)
0