Last active
May 22, 2024 07:53
-
-
Save guolinaileen/4632431 to your computer and use it in GitHub Desktop.
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
return addNodes(l1, l2, 0); | |
} | |
ListNode *addNodes(ListNode *l1, ListNode *l2, int carry) | |
{ | |
if(!l1 && !l2 && carry==0) return NULL; | |
int a=0, b=0; | |
if(l1){ a=l1->val; } | |
if(l2){ b=l2->val; } | |
int value=a+b+carry; | |
ListNode *head=new ListNode(value%10); | |
head->next=addNodes(l1? l1->next: NULL , l2?l2->next:NULL, value/10); | |
return head; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { | |
* val = x; | |
* next = null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
return calculate(l1, l2, 0); | |
} | |
ListNode calculate(ListNode l1, ListNode l2, int carry) | |
{ | |
if(l1==null&&l2==null&&carry==0) return null; | |
if(l1==null&&l2==null&&carry!=0) return new ListNode(1); | |
int temp=(l1==null? 0: l1.val)+ (l2==null? 0: l2.val)+ carry; | |
ListNode result=new ListNode(temp%10); | |
result.next=calculate(l1==null? null: l1.next, l2==null? null: l2.next, temp/10); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment