[c++] 7-line solution


  • 0
    G
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        	ListNode prehead(0), *iter = &prehead;
        	int carry = 0;    
        	for (;l1 || l2 || carry; l1 = (l1 ? l1->next : 0), l2 = (l2 ? l2->next : 0), iter = iter->next) {
        		int digit = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
        		carry = digit >= 10;
    			iter->next = new ListNode(digit % 10);
        	}  
        	return prehead.next;
        }

Log in to reply
 

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