Skip to content

Latest commit

 

History

History
64 lines (52 loc) · 1.61 KB

File metadata and controls

64 lines (52 loc) · 1.61 KB

2. Add Two Numbers

    1. Add Two Numbers [Linked List] [Math] [Medium]

Tags

  • [Linked List] [Math] [Medium]

Problem

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.

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        if (l1 == nullptr || l2 == nullptr) {
            return l1 != nullptr ? l1 : l2;
        }
        
        int carry = 0;
        ListNode dummy(-1), *node = &dummy;
        while (l1 != nullptr || l2 != nullptr) {
            int v1 = l1 != nullptr ? l1->val : 0;
            int v2 = l2 != nullptr ? l2->val : 0;
            int sum = v1 + v2 + carry;
            carry = sum / 10;
            node->next = new ListNode(sum % 10);
            node = node->next;
            l1 = l1 != nullptr ? l1->next : nullptr;
            l2 = l2 != nullptr ? l2->next : nullptr;
        }
        
        if (carry > 0) {
            node->next = new ListNode(carry);
        }
        
        return dummy.next;
    }
};

Time Complexity

  • $O(n)$

Space Complexity

  • $O(1)$

Notes

  • Two Pointers, 20190326.