LeetCode 2. Add Two Numbers 原创Java参考解答

LeetCode 2. Add Two Numbers 原创Java参考解答

问题描述

https://leetcode.com/problems/add-two-numbers/

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解题思路

题目是求做一个以两个链表l1, l2的每一位节点之和作为每一个节点值的新链表。两个链表从左往右,想象成个位、十位、百位相加……该进位时候需要进位。

破此题的关键点:由“个位”节点开始做加法构造新链表,注意分情况计算新链表每一个位置节点的值:两个链表都还有节点时 ((l1.val + l2.val + carry) % 10)、只剩其中一个链表有节点时 ((l1.val + carry) % 10 || (l2.val + carry) % 10)、两个链表都没有节点时 (carry)

参考代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        int carry = 0;

        while (l1 != null && l2 != null) {
            int result = (l1.val + l2.val + carry) % 10;
            ListNode newNode = new ListNode(result); 
            carry = (l1.val + l2.val + carry) / 10;
            current.next = newNode; 
            current = newNode;
            l1 = l1.next;
            l2 = l2.next;            
        }
        
        while (l1 != null) {
            int result = (l1.val + carry) % 10;
            ListNode newNode = new ListNode(result); 
            carry = (l1.val + carry) / 10;
            current.next = newNode; 
            current = newNode;
            l1 = l1.next;
        }
        
        while (l2 != null) {
            int result = (l2.val + carry) % 10;
            ListNode newNode = new ListNode(result); 
            carry = (l2.val + carry) / 10;
            current.next = newNode; 
            current = newNode;
            l2 = l2.next;
        }
        
        if (carry != 0) {
            ListNode newNode = new ListNode(carry); 
            current.next = newNode; 
            current = newNode;
        }

        return dummy.next;
    }
}

相关题目

LeetCode All in One 原创题目讲解汇总

发表评论

电子邮件地址不会被公开。 必填项已用*标注