-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathAddTwoNumbers.java
38 lines (34 loc) · 914 Bytes
/
AddTwoNumbers.java
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
38
package problems.medium;
import problems.utils.ListNode;
/**
* Created by sherxon on 1/1/17.
*/
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null )return l2;
if(l2==null)return l1;
ListNode x=new ListNode(0);
ListNode head=x;
int carry=0;
while(l1!=null || l2!=null){
int val=0;
if(l1==null && l2!=null)
val=l2.val+carry;
else if(l2==null && l1!=null)
val=l1.val+carry;
else
val=l2.val+carry+l1.val;
carry=val/10;
x.next=new ListNode(val%10);
if(l1!=null)
l1=l1.next;
if(l2!=null)
l2=l2.next;
x=x.next;
}
if(carry>0){
x.next=new ListNode(carry);
}
return head.next;
}
}