From 633babf936e614818ab83246e2ab447cdb4016b3 Mon Sep 17 00:00:00 2001 From: Zong <1003160664@qq.com> Date: Wed, 28 Oct 2020 21:38:26 +0800 Subject: [PATCH 1/2] Update 2.add-two-numbers.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加Java、python语言支持 --- problems/2.add-two-numbers.md | 84 +++++++++++++++++++++++++++++++++-- 1 file changed, 80 insertions(+), 4 deletions(-) diff --git a/problems/2.add-two-numbers.md b/problems/2.add-two-numbers.md index ef32a19b2..d2e453439 100644 --- a/problems/2.add-two-numbers.md +++ b/problems/2.add-two-numbers.md @@ -48,11 +48,11 @@ https://leetcode-cn.com/problems/add-two-numbers/ ## 代码 -- 语言支持:JS,C++ +- 语言支持:JS,C++,Java,Python -JavaScript: +JavaScript Code: -```js +```js /** * Definition for singly-linked list. * function ListNode(val) { @@ -102,7 +102,7 @@ var addTwoNumbers = function (l1, l2) { }; ``` -C++ +C++ Code: > C++代码与上面的 JavaScript 代码略有不同:将 carry 是否为 0 的判断放到了 while 循环中 @@ -141,6 +141,82 @@ public: }; ``` + +Java Code: + +```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 Code: + +```py +class Solution(object): + def addTwoNumbers(self, l1, l2): + """ + :type l1: ListNode + :type l2: ListNode + :rtype: ListNode + """ + 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 + +``` + + **复杂度分析** - 时间复杂度:$O(N)$ From a1c6a10473e3c5884fc313f4548780d3f2d29fc4 Mon Sep 17 00:00:00 2001 From: lucifer Date: Thu, 29 Oct 2020 12:02:22 +0800 Subject: [PATCH 2/2] Update 2.add-two-numbers.md --- problems/2.add-two-numbers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/2.add-two-numbers.md b/problems/2.add-two-numbers.md index d2e453439..fda8dae34 100644 --- a/problems/2.add-two-numbers.md +++ b/problems/2.add-two-numbers.md @@ -183,7 +183,7 @@ class Solution { Python Code: ```py -class Solution(object): +class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode