[LeetCode-Java Practice] 02. Add two numbers (medium)

1. Title description

Insert picture description here

2. Problem solving ideas

Since the two input linked lists store the number of digits in reverse order, the numbers at the same position in the two linked lists can be added directly. We traverse the two linked lists at the same time, calculate their sum bit by bit, and add it to the carry value at the current position. Specifically, if the numbers at the corresponding positions of the current two linked lists are n1, n2, and the carry value is carry, their sum is n1+n2+carry; where the numbers at the corresponding positions in the answer linked list are (n1+n2+ carry)% 10, and the new carry value is (n1+n2+carry)/10 rounded down.
If the lengths of the two linked lists are different, it can be considered that there are several 0s behind the short-length linked list.
In addition, if there is carry> 0 after the traversal of the linked list, a node needs to be appended to the answer linked list, and the value of the node is carry.

3. Code implementation

class Solution {
    
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    
        ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
    
    
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;
            if (head == null) {
    
    
                head = tail = new ListNode(sum % 10);
            } else {
    
    
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum / 10;
            if (l1 != null) {
    
    
                l1 = l1.next;
            }
            if (l2 != null) {
    
    
                l2 = l2.next;
            }
        }
        if (carry > 0) {
    
    
            tail.next = new ListNode(carry);
        }
        return head;
    }
}

Guess you like

Origin blog.csdn.net/weixin_48683410/article/details/113048117