Leetcode 2. Add Two Numbers 题解

最后编辑于: 2016-03-29

题目链接

我的解

设置一个carry变量来记录进位,注意处理一些细节:

44ms

/**
 * 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) {
        ListNode res_head(0);
        ListNode* l_res = &res_head;
        unsigned int carry = 0;
        while(l1 || l2)
        {
            l_res->next = new ListNode(0);
            l_res = l_res->next;
            unsigned int tmp_sum = (l1? l1->val:0) + (l2? l2->val:0) + carry;
            l_res->val = tmp_sum%10;
            carry = tmp_sum/10;
            if (l1)
                l1 = l1->next;
            if (l2)
                l2 = l2->next;

        }
        if (carry != 0)
            l_res->next = new ListNode(carry);
        return res_head.next;
    }
};
(全文完)

蜀ICP备18008150号-1

♥ It's Easy if You Try