Skip to content

Commit 35b7a4a

Browse files
committed
solve 2: add two numbers
1 parent 50326a6 commit 35b7a4a

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

vscode/2.add-two-numbers.java

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
* @lc app=leetcode id=2 lang=java
3+
*
4+
* [2] Add Two Numbers
5+
*
6+
* https://leetcode.com/problems/add-two-numbers/description/
7+
*
8+
* algorithms
9+
* Medium (30.61%)
10+
* Total Accepted: 801.6K
11+
* Total Submissions: 2.6M
12+
* Testcase Example: '[2,4,3]\n[5,6,4]'
13+
*
14+
* You are given two non-empty linked lists representing two non-negative
15+
* integers. The digits are stored in reverse order and each of their nodes
16+
* contain a single digit. Add the two numbers and return it as a linked list.
17+
*
18+
* You may assume the two numbers do not contain any leading zero, except the
19+
* number 0 itself.
20+
*
21+
* Example:
22+
*
23+
*
24+
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
25+
* Output: 7 -> 0 -> 8
26+
* Explanation: 342 + 465 = 807.
27+
*
28+
*
29+
*/
30+
/**
31+
* Definition for singly-linked list.
32+
* public class ListNode {
33+
* int val;
34+
* ListNode next;
35+
* ListNode(int x) { val = x; }
36+
* }
37+
*/
38+
class Solution {
39+
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
40+
int sum = 0;
41+
ListNode p1 = l1;
42+
ListNode p2 = l2;
43+
ListNode dummy = new ListNode(-1);
44+
ListNode p = dummy;
45+
46+
while (p1 != null || p2 != null) {
47+
sum /= 10;
48+
49+
if (p1 != null) {
50+
sum += p1.val;
51+
p1 = p1.next;
52+
}
53+
54+
if (p2 != null) {
55+
sum += p2.val;
56+
p2 = p2.next;
57+
}
58+
59+
p.next = new ListNode(sum % 10);
60+
p = p.next;
61+
}
62+
63+
if (sum / 10 == 1) {
64+
p.next = new ListNode(1);
65+
}
66+
67+
return dummy.next;
68+
}
69+
}
70+

0 commit comments

Comments
 (0)