From 1cf14b1d54f371929c1597b0fa11152de6156cae Mon Sep 17 00:00:00 2001 From: Zong <1003160664@qq.com> Date: Wed, 29 Jul 2020 14:13:03 +0800 Subject: [PATCH] Update 0002-Add-Two-Numbers.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加Java、Python代码实现 --- .../Article/0002-Add-Two-Numbers.md | 64 ++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/0002-Add-Two-Numbers/Article/0002-Add-Two-Numbers.md b/0002-Add-Two-Numbers/Article/0002-Add-Two-Numbers.md index 34744d1..275e837 100644 --- a/0002-Add-Two-Numbers/Article/0002-Add-Two-Numbers.md +++ b/0002-Add-Two-Numbers/Article/0002-Add-Two-Numbers.md @@ -32,7 +32,8 @@ ### 代码实现 -``` +#### C++ +```c++ /// 时间复杂度: O(n) /// 空间复杂度: O(n) /** @@ -70,7 +71,68 @@ public: }; ``` +#### Java +```java +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + ListNode dummyHead = new ListNode(0); + ListNode cur = dummyHead; + int carry = 0; + while(l1 != null || l2 != null) + { + int sum = carry; + if(l1 != null) + { + sum += l1.val; + l1 = l1.next; + } + if(l2 != null) + { + sum += l2.val; + l2 = l2.next; + } + // 创建新节点 + carry = sum / 10; + cur.next = new ListNode(sum % 10); + cur = cur.next; + + } + if (carry > 0) { + cur.next = new ListNode(carry); + } + return dummyHead.next; + } +} +``` +#### Python +```python +class Solution(object): + def addTwoNumbers(self, l1, l2): + res=ListNode(0) + head=res + carry=0 + while l1 or l2 or carry!=0: + sum=carry + if l1: + sum+=l1.val + l1=l1.next + if l2: + sum+=l2.val + l2=l2.next + # set value + if sum<=9: + res.val=sum + carry=0 + else: + res.val=sum%10 + carry=sum//10 + # creat new node + if l1 or l2 or carry!=0: + res.next=ListNode(0) + res=res.next + return head +``` ![](../../Pictures/qrcode.jpg)