2. Add Two Numbers

Description

https://leetcode.com/problems/add-two-numbers/
题目大意:
给定两个非空链表,表示两个非负整数。数字以相反的顺序存储,每个结点包含一个数字。对这两个非负整数求和并将其作为链表返回。除了数字0本身,这两个非负整数不包含前导0。

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

Solving Ideas

模拟大数加法
https://leetcode.com/problems/add-two-numbers/solution/

Solution

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

        while (p1 != null || p2 != null) {
            int x = (p1 != null) ? p1.val : 0;
            int y = (p2 != null) ? p2.val : 0;
            int sum = x + y + carry;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            carry = sum / 10;
            if (p1 != null) p1 = p1.next;
            if (p2 != null) p2 = p2.next;
        }
        if (carry > 0) cur.next = new ListNode(carry);

        return res.next;
    }
}

你可能感兴趣的:(Leetcode,LeetCode)