程式語言 - LeetCode - C++ - 2. Add Two Numbers



參考資訊:
https://www.cnblogs.com/grandyang/p/4129891.html

題目:


解答:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode *l1, ListNode *l2) {
        int carry = 0;
        ListNode *r = new ListNode(0, 0);
        ListNode *cur = r;

        while (l1 || l2) {
            int v1 = l1 ? l1->val : 0;
            int v2 = l2 ? l2->val : 0;
            int sum = v1 + v2 + carry;

            carry = sum / 10;
            cur->next = new ListNode(sum % 10, 0);
            cur = cur->next;

            if (l1) {
                l1 = l1->next;
            }
            if (l2) {
                l2 = l2->next;
            }
        }

        if (carry) {
            cur->next = new ListNode(1, 0);
        }
        return r->next;
    }
};