-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathAddTwoNumbers.java
More file actions
38 lines (37 loc) · 985 Bytes
/
AddTwoNumbers.java
File metadata and controls
38 lines (37 loc) · 985 Bytes
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
/*
The paradigm of this solution and that of AddBinary3.java are similar.
*/
/**
* 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
ListNode header = new ListNode(-1);
ListNode prev = header;
int sum=0;
while(l1!=null || l2!=null || sum>0){
if(l1!=null)
sum+=l1.val;
if(l2!=null)
sum+=l2.val;
int val = sum%10;
sum = sum/10;
ListNode current = new ListNode(val);
prev.next = current;
prev = current;
l1 = l1==null?l1:l1.next;
l2 = l2==null?l2:l2.next;
}
return header.next;
}
}