/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = l1;
while(1){
l1->val +=l2->val;
if(l1->next == NULL){
if(l2->next == NULL){
if(l1->val>9){
l1->next = new ListNode(1);
l1->val %=10;
}
return ans;
}
l1->next = new ListNode(0);
}
if(l2->next==NULL){
l2->next = new ListNode(0);
}
l1->next->val+=l1->val/10;
l1->val%=10;
l1=l1->next;
l2=l2->next;
}
}
};
1559 / 1559 test cases passed.
Status: Accepted
Runtime: 35 ms
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *ansd =new ListNode(0);
ListNode *ans = ansd;
int as = 0;
while(l1||l2||as!=0){
if(l1){
as+=l1->val;
l1 = l1->next;
}
if(l2){
as+=l2->val;
l2 = l2->next;
}
if(as>9){
ans->next = new ListNode(as-10);
as = 1;
}else{
ans->next = new ListNode(as);
as = 0;
}
ans = ans->next;
}
return ansd->next;
}
};
1562 / 1562 test cases passed.
Status: Accepted
Runtime: 32 ms
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *ans = l1;
while(l1->next&&l2->next){
l1->val+=l2->val;
if(l1->val>9){
l1->val-=10;
l1->next->val+=1;
}
l1 = l1->next;
l2 = l2->next;
}
while(l1->next == NULL && l2 -> next){
l1 ->next = new ListNode(0);
l1 ->val += l2 ->val;
if(l1 -> val>9){
l1 ->val -= 10;
l1 ->next ->val +=1;
}
l1 = l1 ->next;
l2 = l2 ->next;
}
{
l1->val+=l2->val;
while(l1->val>9){
l1->val-=10;
if(l1->next == NULL){
l1->next = new ListNode(0);
}
l1->next->val+=1;
l1=l1->next;
}
}
return ans;
}
};
1562 / 1562 test cases passed.
Status: Accepted
Runtime: 32 ms