Super simple C solution in 16ms!


  • -1
    C
    ListNode * addTwoNumbers(ListNode* l1, ListNode* l2){
    	struct ListNode* result = (struct ListNode*) malloc(sizeof(struct ListNode));
    	struct ListNode *head = result;
    	int carrybit=0;
    	int sum;
    	while(l1 || l2){ //end when both lists are null
    		if(!l1){
    			sum = (l2->val + carrybit);
    			l2=l2->next;
    		}else if(!l2){
    			sum = (l1->val + carrybit);
    			l1=l1->next;
    		}else{
    			sum = (l1->val + l2->val + carrybit);
    			l1=l1->next;
    			l2=l2->next;
    		}
    		if(sum>=10)
    			carrybit=1; //determine carry
    		else
    			carrybit=0;
    		result->val = sum % 10;// take out ones position
    		if((l1 || l2)){
    			result->next = (struct ListNode*)malloc(sizeof(struct ListNode)); //malloc next only if l1 and l2 are not NULL
    			result = result->next;
    		}
    	}
    	if(carrybit){ //for the last possible carry bit
    		result->next = (struct ListNode*)malloc(sizeof(struct ListNode));
    		result->next->val = 1;
    		result->next->next = NULL;
    	}else
    		result->next = NULL;
    	return head;
    }

Log in to reply
 

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