Add Two Numbers

题目:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

分析:

用一个carry位来表示进位,但是记住要先+carry求余数,然后再更新carry的值。

解法:

class Solution {
public:
    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the sum list of l1 and l2 
     */
    ListNode *addLists(ListNode *l1, ListNode *l2) {
        if (l1 == NULL) {
            return l2;
        }
        if (l2 == NULL) {
            return l1;
        }

        int carry = 0;
        ListNode dummy(0);
        ListNode* curr = &dummy;
        while (l1 != NULL && l2 != NULL) {

            curr->next = new ListNode( (l1->val + l2->val + carry) % 10 );
            carry = (l1->val + l2->val + carry) / 10;
            curr = curr->next;
            l1 = l1->next;
            l2 = l2->next;
        }

        while (l1 != NULL) {

            curr->next = new ListNode( (l1->val + carry) % 10 );
            carry = (l1->val + carry) / 10;

            curr = curr->next;
            l1 = l1->next;
        }

        while (l2 != NULL) {

            curr->next = new ListNode( (l2->val + carry) % 10 );
            carry = (l2->val + carry) / 10;

            curr = curr->next;
            l2= l2->next;
        }

        if (carry != 0) {
            curr->next = new ListNode(carry);
        }

        return dummy.next;
    }
};

results matching ""

    No results matching ""