Skip to content

Commit 890a768

Browse files
author
applewjg
committed
Add Two Numbers
1 parent c9d1499 commit 890a768

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

AddTwoNumbers.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 13, 2014
4+
Problem: Add Two Numbers
5+
Difficulty: easy
6+
Source: https://oj.leetcode.com/problems/add-two-numbers/
7+
Notes:
8+
You are given two linked lists representing two non-negative numbers.
9+
The digits are stored in reverse order and each of their nodes contain a single digit.
10+
Add the two numbers and return it as a linked list.
11+
12+
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
13+
Output: 7 -> 0 -> 8
14+
15+
Solution: dummy head...
16+
17+
*/
18+
/**
19+
* Definition for singly-linked list.
20+
* public class ListNode {
21+
* int val;
22+
* ListNode next;
23+
* ListNode(int x) {
24+
* val = x;
25+
* next = null;
26+
* }
27+
* }
28+
*/
29+
public class Solution {
30+
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
31+
ListNode dummy = new ListNode(0);
32+
ListNode cur = dummy;
33+
int carry = 0;
34+
while (l1 != null || l2 != null || carry != 0) {
35+
int sum = carry;
36+
if (l1 != null) {
37+
sum += l1.val;
38+
l1 = l1.next;
39+
}
40+
if (l2 != null) {
41+
sum += l2.val;
42+
l2 = l2.next;
43+
}
44+
carry = sum/10;
45+
sum = sum%10;
46+
ListNode node = new ListNode(sum);
47+
cur.next = node;
48+
cur = cur.next;
49+
}
50+
return dummy.next;
51+
}
52+
}

0 commit comments

Comments
 (0)