Leetcode Add Two Numbers problem solution in C programming

In the Leetcode Add Two Numbers problem solution in C programming You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Leetcode Add Two Numbers problem solution in C programming

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int carry = 0, sum;
    struct ListNode *result = (struct ListNode*) malloc(sizeof(struct ListNode));
    struct ListNode *current = result;
    struct ListNode *new;
    result->val = 0;
    result->next = NULL;
    
    if (!l1 && !l2) {
        goto end;
    }
    
    while (true) {
        sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
        current->val = sum % 10;
        carry = sum >= 10 ? 1 : 0;
        
        l1 = l1 ? l1->next : l1;
        l2 = l2 ? l2->next : l2;
        
        if (!l1 && !l2 && !carry) {
            break;
        }
        
        new = (struct ListNode*) malloc(sizeof(struct ListNode));
        new->next = NULL;
        current->next = new;
        current = new;
    }
    
    end:
    return result;
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *