-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd Two Numbers
37 lines (36 loc) · 995 Bytes
/
Add Two Numbers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tem1=l1;
ListNode tem2=l2;
ListNode newnode=new ListNode(0);
ListNode curr=newnode;
int carry=0;
while(tem1!=null || tem2!=null){
int sum=carry;
if(tem1!=null) {
sum+=tem1.val;
tem1=tem1.next;
}
if(tem2!=null) {
sum+=tem2.val;
tem2=tem2.next;
}
curr.next=new ListNode(sum%10);
carry=sum/10;
curr=curr.next;
}
if(carry!=0){
curr.next=new ListNode(carry);
}
return newnode.next;
}
}