[leetCode 丶 20241202] 2. 两数相加

原题: 2.两数相加


描述:

描述


个人版答案

执行用时: 2 ms 执行内存消耗: 43.57 M

/**
 * 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) {
        // 问题解
        ListNode soultion;
        // 临时
        List<Integer> temp = new ArrayList<>();
        // 终止信号
        Integer next = 0;
        // 循环
        while (true) {
            if (next == 0 && Objects.isNull(l1) && Objects.isNull(l2)) {
                break;
            }
            // 临时变量
            int a = 0, b = 0;
            if (Objects.nonNull(l1)) {
                a = l1.val;
                l1 = l1.next;
            }
            if (Objects.nonNull(l2)) {
                b = l2.val;
                l2 = l2.next;
            }
            int i = a + b + next;
            // 判断是否需要进位
            if (i >= 10) {
                next = 1;
                temp.add(i - 10);
            } else {
                next = 0;
                temp.add(i);
            }
        }
        if (temp.size() == 1) {
            return new ListNode(temp.get(0));
        }
        soultion = new ListNode(temp.get(temp.size() - 1));
        for (int i = temp.size() - 2; i >= 0; i--) {
            soultion = new ListNode(temp.get(i), soultion);
        }
        return soultion;
    }
}

优秀解法

执行耗时: 1 ms

/**
 * 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 n = 0;
        int n1 = 0;
        int n2 = 0;
        int j = 0;
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        while(cur1 != null || cur2!=null){
            n1 = cur1!=null?cur1.val:0;
            n2 = cur2!=null ? cur2.val:0;
            n = n1 + n2 +j;
          
            cur.next = new ListNode(n%10);
            j = n/10;
            cur = cur.next;
            cur1= cur1 != null ?cur1.next:null;
             cur2 = cur2!=null ?cur2.next:null;          
        }
        if(j == 1){
            cur.next = new ListNode(1);
        }
        return pre.next;
    }
}

个人解题思路与优秀答案解析

题目分析及个人版思路

  1. 偷个懒, 顺序做第二题
  2. 其实就是简单的链表求和. 因为保证数字不以0开头. 那么我们就可以直接个位数加法走起. 循环按照最长的来就行. 所以直接while(true). 直到达到停止条件.
  3. 计算不用多说, 就是简单的进位时候需要注意减去10. 下一把要加上10. 循环终止条件也要带上这个10是否进位哦. 要不就少一位了.
  4. 话不多说, 上代码...

进阶版思路
嘿嘿...差不多差不多.