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)