# LCP002 LeetCode 2. Add Two Numbers

Total Accepted: 147076 Total Submissions: 627191 Difficulty: Medium

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Subscribe to see which companies asked this question

class Solution {
public:
ListNode* add(ListNode* l1, ListNode* l2, bool carryBit)
{
if (l1 != NULL || l2 != NULL)
{
if (l1 == NULL)
{
l1 = new ListNode (0);
}
if (l2 == NULL)
{
l2 = new ListNode (0);
}
l1->val += l2->val;
if (carryBit)
{
l1->val += 1;
}
carryBit = l1->val / 10;
l1->val %= 10;
}
else if (carryBit)
{
ListNode* newBit = new ListNode (1);
return newBit;
}
return l1;
}
{
return l1;
}
};

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
}

#### 【LeetCode】2. Add Two Numbers 解题报告

2016-10-24 19:46:34

2016-04-14 21:25:50

#### leetcode 2. Add Two Numbers C语言实现

2017-03-31 19:48:34

#### LeetCode 2. Add Two Numbers（C++）

2017-03-21 20:11:37

2016-11-21 12:05:45

2016-06-01 16:34:44

2016-05-01 19:30:16

#### 【LeetCode with Python】 Add Two Numbers

2014-06-27 18:11:19

#### [Leetcode] Add Two Numbers Python实现 详细讲解

2017-02-12 16:54:13

#### [LeetCode] 002. Add Two Numbers (Medium) (C++/Java/Python)

2015-02-27 12:43:08