Skip to content

Commit 810ee7e

Browse files
Added Leetcode Add Two Numbers (dubesar#614)
1 parent d090c5f commit 810ee7e

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import java.util.*;
2+
3+
class ListNode {
4+
int val;
5+
ListNode next;
6+
ListNode() {}
7+
ListNode(int val) { this.val = val; }
8+
ListNode(int val, ListNode next) {
9+
this.val = val; this.next = next;
10+
}
11+
}
12+
13+
class Solution {
14+
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
15+
ListNode l3 = new ListNode();
16+
ListNode head = l3;
17+
int num = 0;
18+
int carry = 0;
19+
20+
while(l1 != null || l2 != null){
21+
if(l1 != null && l2 != null)
22+
num = l1.val + l2.val + carry;
23+
else if(l1 == null)
24+
num = l2.val + carry;
25+
else if(l2 == null)
26+
num = l1.val + carry;
27+
28+
if(l1 != null)
29+
l1 = l1.next;
30+
if(l2 != null)
31+
l2 = l2.next;
32+
33+
if(num > 9){
34+
l3.val = num%10;
35+
carry = 1;
36+
}
37+
else{
38+
l3.val = num;
39+
carry = 0;
40+
}
41+
42+
if(l1 != null || l2 != null){
43+
l3.next = new ListNode();
44+
l3 = l3.next;
45+
}
46+
}
47+
if(carry == 1){
48+
l3.next = new ListNode(1);
49+
}
50+
return head;
51+
}
52+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
2+
3+
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
4+
5+
Example 1:
6+
Input: l1 = [2,4,3], l2 = [5,6,4]
7+
Output: [7,0,8]
8+
Explanation: 342 + 465 = 807.
9+
10+
Example 2:
11+
Input: l1 = [0], l2 = [0]
12+
Output: [0]
13+
14+
Example 3:
15+
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
16+
Output: [8,9,9,9,0,0,0,1]
17+
18+
Constraints:
19+
The number of nodes in each linked list is in the range [1, 100].
20+
0 <= Node.val <= 9
21+
It is guaranteed that the list represents a number that does not have leading zeros.

0 commit comments

Comments
 (0)