C in 29ms


  • 0
    R
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode *l3 = l1 ? l1 : l2;
        struct ListNode *carry = l1 ? l2 : l1;
        struct ListNode *result = l3;
        struct ListNode *pre = l3;
        int sum = 0;
        while ((l1 != NULL) || (l2 != NULL)) {
            sum /= 10;
            if (l1 != NULL) {
                sum += l1->val;
                l1 = l1->next;
            }
            if (l2 != NULL) {
                sum += l2->val;
                l2 = l2->next;
            }
            l3->val = sum % 10;
            if (l3->next == NULL) {
                l3->next = l1 ? l1 : l2;
            }
            pre = l3;
            l3 = l3->next;
            
        }
        // 最后一位进位
        if (sum / 10 != 0) {
            carry->val = sum / 10;
            l3 = carry;
            l3->next = NULL;
            pre->next = l3;
        }
        
        return result;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.