# Middle-题目110：2. Add Two Numbers

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

import java.math.BigInteger;

public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
BigInteger num1 = BigInteger.ZERO;
BigInteger num2 = BigInteger.ZERO;
BigInteger temp = BigInteger.ONE;

while(l1!=null) {
//num1+=temp*l1.val;
temp=temp.multiply(BigInteger.TEN);
l1=l1.next;
}
temp=BigInteger.ONE;
while(l2!=null) {
temp=temp.multiply(BigInteger.TEN);
l2=l2.next;
}
BigInteger sum = num1.add(num2);
if(sum.compareTo(BigInteger.ZERO)==0)
return new ListNode(0);
else {
ListNode l = new ListNode(sum.mod(BigInteger.TEN).intValue());
ListNode p=l;
while(sum.compareTo(BigInteger.ZERO)!=0) {
sum=sum.divide(BigInteger.TEN);
if(sum.compareTo(BigInteger.ZERO)!=0) {
p.next = new ListNode(sum.mod(BigInteger.TEN).intValue());
p=p.next;
}
}
return l;
}
}
}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* result = l1 ? l1 : l2;
struct ListNode* carry = l1 ? l2 : l1;
struct ListNode* node = result;
struct ListNode* tmp;
int c = 0;
int s;
while (l1 || l2) {
s = c;
if (l1) { s += l1->val; l1=l1->next; }
if (l2) { s += l2->val; l2=l2->next; }
c = s > 9 ? 1 : 0;
node->val = c ? s - 10 : s;
if (l1) {
node = node->next = l1;
} else if (l2) {
node = node->next = l2;
} else {
node->next = NULL;
}
}
if (c) {
carry->val = c;
node->next = carry;
node = node->next;
}
node->next = NULL;
return result;
}

#### 2、add two numbers（python）

2016-09-18 21:49:47

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

2016-10-24 19:46:34

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

2017-02-12 16:54:13

#### 【python】【leetcode】【算法题目2—Add Two Numbers】

2016-11-21 12:05:45

#### leetcode（二）—— Add Two Numbers（Python/C++）

2016-04-11 09:48:50

#### leetcode 2：Add Two Numbers(C语言)

2016-09-10 00:52:57

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

2017-03-21 20:11:37

#### leetcode_c++：链表：add two numbers（002）

2016-05-03 09:49:29

#### [LeetCode][2]Add Two Numbers解析 -Java实现

2016-06-01 16:34:44

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

2014-06-27 18:11:19