Quellcode durchsuchen

#feat:leetcode p2题题解

yangyi vor 2 Wochen
Ursprung
Commit
58b026b4fa
1 geänderte Dateien mit 63 neuen und 0 gelöschten Zeilen
  1. 63 0
      src/leetcode/p2/Solution.java

+ 63 - 0
src/leetcode/p2/Solution.java

@@ -0,0 +1,63 @@
+package leetcode.p2;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2025/8/13 11:34
+ * @Description: https://leetcode.cn/problems/add-two-numbers/description/
+ * 2. 两数相加
+ */
+
+/**
+ * Definition for singly-linked list.
+ * public class ListNode {
+ *     int val;
+ *     ListNode next;
+ *     ListNode() {}
+ *     ListNode(int val) { this.val = val; }
+ *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
+ * }
+ */
+class Solution {
+    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
+        int count = 0;
+        ListNode head = new ListNode();
+        ListNode cur = head;
+        while(true){
+            int v;
+            if(l1 != null && l2 != null){
+                //都不为null则相加
+                v = l1.val +l2.val + count;
+                l1 = l1.next;
+                l2 = l2.next;
+            }else if (l1 == null && l2 == null){
+                break;
+            }else if (l1 == null){
+                v = l2.val + count;
+                l2 = l2.next;
+            }else{
+                v = l1.val + count;
+                l1 = l1.next;
+            }
+            cur.next = new ListNode(v % 10);
+            cur = cur.next;
+            if (v >= 10){
+                count = 1;
+            }else{
+                count = 0;
+            }
+        }
+        if (count == 1){
+            cur.next = new ListNode(1);
+        }
+        return head.next;
+    }
+}
+class ListNode {
+      int val;
+      ListNode next;
+      ListNode() {}
+      ListNode(int val) { this.val = val; }
+      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
+  }