-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbers.java
More file actions
48 lines (42 loc) · 1012 Bytes
/
AddTwoNumbers.java
File metadata and controls
48 lines (42 loc) · 1012 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
39
40
41
42
43
44
45
46
47
48
package com.mirraico.leetcode;
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ptr1 = l1, ptr2 = l2;
ListNode head = new ListNode(-1), ansPtr = head;
int carry = 0;
while(ptr1 != null && ptr2 != null) {
int val = ptr1.val + ptr2.val + carry;
carry = val / 10;
val %= 10;
ansPtr.next = new ListNode(val);
ansPtr = ansPtr.next;
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
while(ptr1 != null) {
int val = ptr1.val + carry;
carry = val / 10;
val %= 10;
ansPtr.next = new ListNode(val);
ansPtr = ansPtr.next;
ptr1 = ptr1.next;
}
while(ptr2 != null) {
int val = ptr2.val + carry;
carry = val / 10;
val %= 10;
ansPtr.next = new ListNode(val);
ansPtr = ansPtr.next;
ptr2 = ptr2.next;
}
if(carry == 1) ansPtr.next = new ListNode(1);
return head.next;
}
public static void main(String[] args) {
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; next = null; }
}