diff --git a/problems/2.add-two-numbers.md b/problems/2.add-two-numbers.md index ef32a19b2..fda8dae34 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: + 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)$