Force button-2. Add two numbers

2. Add two numbers

Title description:

Two non-empty linked lists are given to represent two non-negative integers. Among them, their respective digits are stored in reverse order, and each node can only store one digit.

If we add these two numbers together, a new linked list will be returned to represent their sum.

You can assume that none of these numbers start with 0 except for the number 0.

Example:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

Solution:
Because the linked list starts from the first node and goes from the position to the high position. Therefore, you only need to traverse from the beginning to the end and add them. If there is a carry, add it to the next pair of nodes.

class Solution {
    
    
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    
        //结果链表的链表头
        ListNode result = new ListNode(0);
        //指向上述链表当前节点
        ListNode cur = result;
        //进位
        int carry = 0;
        while (l1!=null || l2!=null){
    
    
            int x = l1==null ? 0 : l1.val;
            int y = l2==null ? 0 : l2.val;
            //求和,对应位的数字加前一位的进位
            int sum = x + y + carry;

            carry = sum/10;
            sum = sum%10;
            cur.next = new ListNode(sum);

            //后移
            cur = cur.next;
            if (l1 != null){
    
    
                l1 = l1.next;
            }
            if (l2 != null){
    
    
                l2 = l2.next;
            }
        }
        //最后一步加完后如果有进位
        if (carry == 1) {
    
    
            cur.next = new ListNode(carry);
        }
        if (result.next != null){
    
    
            //让result后移,避免出现[0 7 0 8]这种情况
            result = result.next;
        }
        return  result;
    }
}

Guess you like

Origin blog.csdn.net/weixin_44829930/article/details/109818155