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

public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        
        ListNode temp = null, res = null, prev = null;
        int sum = 0, carry = 0;
        
        while(l1!=null || l2!=null){
            
            sum = carry + (l1!=null ? l1.val : 0) + (l2!=null ? l2.val : 0);
            carry = (sum >= 10) ? 1 : 0;
            sum = sum % 10;
            
            temp = new ListNode(sum);
            
            if(res == null){
                res = temp;
            }
            else
            {
                prev.next = temp;
            }
            prev = temp;
            
            if(l1!=null)
                l1 = l1.next;
            if(l2!=null)
                l2 = l2.next;
        }
        if(carry>0){
            temp.next = new ListNode(carry);
        }
        
        return res;
    }
}

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 *