【LeetCode 刷题】2. Add Two Numbers

in 编程 with 0 comment

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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

没有接触过链表,所以是抄了一个大佬的作业。

Runtime: 4 ms
Memory Usage: 45.5 MB

/**
 * 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) {
        int curr = 0;  // 当前位数字
        int carry = 0;  // 进位
        ListNode dummy = new ListNode(0);
        ListNode node = dummy;
        while (l1 != null && l2 != null) {
            curr = l1.val + l2.val + carry;
            carry = curr / 10;
            curr %= 10;
            node.next = new ListNode(curr);
            node = node.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1 != null) {
            curr = l1.val + carry;
            carry = curr / 10;
            curr %= 10;
            node.next = new ListNode(curr);
            node = node.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            curr = l2.val + carry;
            carry = curr / 10;
            curr %= 10;
            node.next = new ListNode(curr);
            node = node.next;
            l2 = l2.next;
        }
        if (carry > 0) {
            node.next = new ListNode(carry);
            node = node.next;
        }
        return dummy.next;
    }
}
Responses