Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added python code add two numbers #19

Merged
merged 2 commits into from
Dec 6, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/linked-list/add-two-numbers.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ defaultValue="java"
values={[
{ label: 'Java', value: 'java', },
{ label: 'C++', value: 'cpp', },
{ label: 'Python', value: 'python', },
]
}>
<TabItem value="java">
Expand Down Expand Up @@ -86,6 +87,33 @@ public:
};
```

</TabItem>
<TabItem value="python">

```python
# Add Two Numbers
# 跟Add Binary 很类似
# 时间复杂度O(m+n),空间复杂度O(1)
class Solution:
def addTwoNumbers(self, l1, l2):
dummy = ListNode(-1) # 头节点
carry = 0
prev = dummy
pa, pb = l1, l2
while pa is not None or pb is not None:
ai = 0 if pa is None else pa.val
bi = 0 if pb is None else pb.val
value = (ai + bi + carry) % 10
carry = (ai + bi + carry) / 10
soulmachine marked this conversation as resolved.
Show resolved Hide resolved
prev.next = ListNode(value) # 尾插法
pa = None if pa is None else pa.next
pb = None if pb is None else pb.next
prev = prev.next
if carry > 0:
prev.next = ListNode(carry)
return dummy.next
```

</TabItem>
</Tabs>

Expand Down