-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathaddTwoNumbers.java
43 lines (35 loc) · 941 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
39
40
41
42
43
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p1 = l1, p2 = l2;
ListNode result = new ListNode(-1);
ListNode p3 = result;
int carry = 0;
while(p1 != null || p2!= null)
{
if(p1 != null)
{
carry += p1.val;
p1 = p1.next;
}
if(p2 != null)
{
carry += p2.val;
p2 = p2.next;
}
p3.next = new ListNode(carry%10);
carry /= 10;
p3 = p3.next;
}
if(carry == 1)
p3.next = new ListNode(1);
return result.next;
}
}