The second question I'm trying to do

Give you two non-empty linked lists, representing two non-negative integers. Each digit of them is stored in reverse order, and each node can only store one digit.

Please add two numbers together and return a linked list representing the sum in the same form.

You can assume that except for the number 0, neither of these numbers will start with 0.
Insert picture description hereInput: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

        int l1[] = {
    
    2,0,0,8};
        int l2[] = {
    
    8,0,0,2};
        List<Integer> list = new ArrayList<>();
        int i = 0;
        while (l1 != null || l2 != null) {
    
    
            ListNode node = addTwoNumbers(new ListNode(l1.length > i ? l1[i] : 0), new ListNode(l2.length > i ? l2[i] : 0));
            list.add(node.val);
            i++;
            boolean is = i >= Math.max(l1.length, l2.length);
            if (is) {
    
    
                if (node.val == 0) {
    
    
                    list.add(1);
                }
                break;
            }
            if (node.next != null) {
    
    
                l1[i] = l1[i] + node.next.val;
            }
        }
        String temp = "";
        for (int j = list.size() - 1; j >= 0; j--) {
    
    
            temp += list.get(j);
        }
        System.out.println(temp);
  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    
        ListNode node = null, tail = null;
        int curry = 0;
        while (l1 != null && l2 != null) {
    
    
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + curry;
            if (node == null) {
    
    
                node = tail = new ListNode(sum % 10);
            } else {
    
    
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            curry = sum >9?1:0;
            if (l1 != null) {
    
    
                l1 = l1.next;
            }
            if (l2 != null) {
    
    
                l2 = l2.next;
            }
        }
        if (curry > 0) {
    
    
            tail.next = new ListNode(curry);
        }
        return node;
    }

Guess you like

Origin blog.csdn.net/weixin_42789301/article/details/113525100