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,
- Leetcode Add Two Numbers problem solution in C
- Leetcode Add Two Numbers problem solution in C++
- Leetcode Add Two Numbers problem solution in Java
- Leetcode Add Two Numbers problem solution in Python