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); + } + +}