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
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = new ListNode(0);
int sum = 0, carry = 0;
ListNode* res = ans;
while (l1 || l2) {
sum = carry + (l1 ? l1->val : 0) + (l2 ? l2->val : 0);
ans->next = new ListNode(sum%10);
carry = sum/10;
ans = ans->next;
l1 = (l1) ? l1 -> next : NULL;
l2 = (l2) ? l2 -> next : NULL;
}
if (carry)
ans->next = new ListNode(carry);
return res->next;
}
};
Also read,
- Leetcode Add Two Numbers problem solution in C
- Leetcode Add Two Numbers problem solution in Java
- Leetcode Add Two Numbers problem solution in Python
- Leetcode Add Two Numbers problem solution in C#