-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddTwoNumbers.java
More file actions
64 lines (55 loc) · 1.66 KB
/
addTwoNumbers.java
File metadata and controls
64 lines (55 loc) · 1.66 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
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
342 + 465 = 807
Make sure there are no trailing zeros in the output list
So, 7 -> 0 -> 8 -> 0 is not a valid response even though the value is still 807.
*/
public ListNode addTwoNumbers(ListNode a, ListNode b) {
if(a== null && b== null)
return null;
if(a==null)
return b;
if(b==null)
return a;
int carry =0;
ListNode start =new ListNode(-1);
ListNode prev = start;
while(a!=null && b!= null)
{
ListNode l = new ListNode((a.val + b.val+carry)%10);
carry = ( a.val+b.val+carry)/10;
a= a.next; b= b.next;
prev.next = l;
prev= l;
}
if(a==null)
{
while( b!=null)
{
ListNode l = new ListNode((b.val+carry)%10);
carry = (b.val+carry)/10;
prev.next = l;
prev= l;
b=b.next;
}
}
else
{
while( a!=null)
{
ListNode l = new ListNode((a.val+carry)%10);
carry = (a.val+carry)/10;
prev.next = l;
prev= l;
a=a.next;
}
}
if(carry ==1) {
ListNode l = new ListNode(carry);
prev.next = l;
l.next=null;
}
return start.next;
}