-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbers.java
More file actions
81 lines (68 loc) · 1.84 KB
/
AddTwoNumbers.java
File metadata and controls
81 lines (68 loc) · 1.84 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* Leet code problem #2. Add Two Numbers
* https://leetcode.com/problems/add-two-numbers/
*
* Time complexity: O(max(m ,n))
* Space complexity: O(1)
*/
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
ListNode(int x, ListNode next) {
val = x;
this.next = next;
}
}
public class AddTwoNumbers {
public static void main(String[] args) {
int[] nums1 = { 2, 4, 3 };
int[] nums2 = { 5, 6, 4 };
ListNode l1 = getListNode(nums1);
ListNode l2 = getListNode(nums2);
ListNode result = addTwoNumbers(l1, l2);
printList(result);
}
// Creates a list node from array of numbers
public static ListNode getListNode(int[] nums) {
ListNode head = new ListNode(nums[0]);
ListNode curr = head;
for (int i = 1; i < nums.length; i++) {
curr.next = new ListNode(nums[i]);
curr = curr.next;
}
return head;
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode curr = head;
int carry = 0;
while (l1 != null || l2 != null) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return head.next;
}
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
}