I am currently attempting to answer the question Add Two Numbers from leetcode, my solution seems to function as I expect however in cases where my final carry int is needed it is not added to the end of my list in the final if statement.
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
ListNode* ans = l1;
while(l1 || l2){
if(l1 == nullptr) l1 = new ListNode();
if(l1 == nullptr && l2){
l1 -> val = (l2 -> val + carry) % 10;
carry = (carry + l2 -> val) / 10;
l2 = l2 -> next;
}else if(l2 == nullptr && l1){
int tempL1Val = l1 -> val;
l1 -> val = (l1 -> val + carry) % 10;
carry = (carry + tempL1Val) / 10;
}else{
int tempL1Val = l1 -> val;
l1 -> val = (l1 -> val + l2 -> val + carry) % 10;
carry = (tempL1Val + l2 -> val + carry) / 10;
l2 = l2 -> next;
}
l1 = l1 -> next;
}
if(carry){
l1 = new ListNode();
l1 -> val = carry;
}
return ans;
}
};
Testcases where it fails:
l1 = [9,9,9,9,9,9,9]
l2 = [9,9,9,9]
output = [8,9,9,9,0,0,0]
expected_output = [8,9,9,9,0,0,0,1]
I have checked before and after and the new node does exist, however it is not being added to my list when I run the code.
New contributor
ick1salvado is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.