From ba8f4e0ecb472f2c3b00343a6583ccb1bbf9675f Mon Sep 17 00:00:00 2001 From: linlihong <747682928@qq.com> Date: Thu, 22 Aug 2024 17:30:22 +0800 Subject: [PATCH] =?UTF-8?q?2024/8/22=20Hot100=20LinkedList=20=E4=B8=A4?= =?UTF-8?q?=E6=95=B0=E7=9B=B8=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/cool/hot100/linkedlist/Num2.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/main/java/com/cool/hot100/linkedlist/Num2.java diff --git a/src/main/java/com/cool/hot100/linkedlist/Num2.java b/src/main/java/com/cool/hot100/linkedlist/Num2.java new file mode 100644 index 0000000..bba677a --- /dev/null +++ b/src/main/java/com/cool/hot100/linkedlist/Num2.java @@ -0,0 +1,58 @@ +package com.cool.hot100.linkedlist; + +import org.junit.Test; + +public class Num2 { + + /** + * Date 2024/8/22 + * DayNumber 1 + * Hard 2 + * + * @param l1 + * @param l2 + * @return + */ + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + int add = 0; + ListNode node=null; + ListNode head = null; + int up = 0; + + while (l1 != null || l2 != null) { + int num1 = l1 == null ? 0 : l1.val; + int num2 = l2 == null ? 0 : l2.val; + int sum = num1 + num2 + up; + up=sum/10; + sum = sum % 10; + if (head == null) { + head = node=new ListNode(sum); + }else{ + node.next=new ListNode(sum); + node=node.next; + } + if(l1!=null){ + l1=l1.next; + } + if(l2!=null){ + l2=l2.next; + } + } + if(up>0){ + node.next=new ListNode(up); + } + return head; + } + + @Test + public void test() { + ListNode node3 = new ListNode(3); + ListNode node2 = new ListNode(4, node3); + ListNode node1 = new ListNode(2, node2); + ListNode node4 = new ListNode(4); + ListNode node5 = new ListNode(6, node4); + ListNode node6 = new ListNode(5, node5); + addTwoNumbers(node1, node6); + } + +}