Leetcode 2. Add Two Numbers 题解

Last Updated At: 2016-03-29

题目链接

我的解

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

  • NULL作0处理
  • 及时停止移动已到表尾的指针
  • 处理完后要判断 carry 是否为0

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;
    }
};