leetcode 2. Add two numbers (java)

Question description

Difficulty - Medium
leetcode 2. Add two numbers

You are given two non-empty linked lists, representing two non-negative integers. Each of their digits is stored in reverse order, and each node can only store one digit.
Please add two numbers and return a linked list representing the sum in the same form.
You can assume that except for the number 0, neither number will start with a 0.

Example 1:
Insert image 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]

Tip:
The number of nodes in each linked list is in the range [1, 100]
0 <= Node.val <= 9
The question data guarantees that the number represented by the list does not contain leading zeros

Insert image description here

Sentinel Technique

This is a simulation question, simulating the process of manual vertical addition:
from the lowest digit to the highest digit, add them digit by digit. If the sum is greater than or equal to
, keep the single digit, and at the same time advance the previous digit by 1 if there is a carry in the highest digit. , it needs to be added at the front.
When calculating each bit, the carry issue of the previous bit needs to be considered, and the carry value also needs to be updated after the calculation of the current bit.
If the carry value is 1 after both linked lists are traversed, add node 1 to the front of the new linked list
. Regarding linked list issues, there is a common technique: add a virtual head node (sentinel) to help simplify the judgment of boundary situations.

Code demo:

/**
 * 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 dump = new ListNode(0);
        ListNode tmp = dump;
        int t = 0;

        while(l1 != null || l2 != null){
    
    
            int a = l1 != null ? l1.val : 0;
            int b = l2 != null ? l2.val : 0;
            int ans = a + b + t;
            tmp.next = new ListNode(ans % 10);
            tmp = tmp.next;
            t = (ans / 10);
            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        }
        if(t > 0)tmp.next = new ListNode(t);
        return dump.next;
    }
}

Special Topic on Recursive Algorithms

leetcode-779. The Kth grammar symbol

leetcode669. Pruning a binary search tree

leetcode687. The longest path with the same value

Guess you like

Origin blog.csdn.net/SP_1024/article/details/132733978