My cpp solution (51ms)


  • 0
    A
    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            ListNode *p1=l1,*p2=l2;
            ListNode *ptmp;
            unsigned int carry=0;
            unsigned int r;
            while(p1&&p2){
                r=(p2->val+p1->val+carry)%10;
                carry=(p2->val+p1->val+carry)/10;
                p1->val=r;
                if(p1&&p1->next==NULL){
                    ptmp=p1;
                }
                p1=p1->next;
                p2=p2->next;
            }
    
            if(p2){
                ptmp->next=p2;
                p1=ptmp->next;
            }
            if(p1==NULL&&p2==NULL&&carry){
                ListNode *node=new ListNode(carry);
                node->next=NULL;
                ptmp->next=node;
                return l1;
            }
            while(p1){
                r=(p1->val+carry)%10;
                carry=(p1->val+carry)/10;
                p1->val=r;
                if(p1->next==NULL&&p1->val==0&&carry){
                    ListNode *node=new ListNode(carry);
                    node->next=NULL;
                    p1->next=node;
                    break;
                }
                p1=p1->next;
            }
            return l1;
        }
    };

  • 0
    E

    I have a similar solution as yours, and combined the case l1 l2 have same length into the second loop to make it a little more concise.

    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            ListNode *result = l1, *l1_prev = 0;
            int carry = 0;
            while (l1 && l2) {
                l1->val += l2->val + carry;
                carry = l1->val / 10;
                l1->val %= 10;
                l1_prev = l1;
                l1 = l1->next;
                l2 = l2->next;
            }
            if (l2) {
                l1_prev->next = l2;
            }
            
            while (carry) {
                if (!l1_prev->next) {
                    l1_prev->next = new ListNode(carry);
                    break;
                }
                l1_prev->next->val += carry;
                carry = l1_prev->next->val / 10;
                l1_prev->next->val %= 10;
                l1_prev = l1_prev->next;
            }
            return result;
        }
    };

Log in to reply
 

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