# LeetCode 两数相加

``````给定两个非空链表来表示两个非负整数。位数按照逆序方式存储，它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

``````
###### 解法一：

``````    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

int tempSum = 0, addSign = 0;

while (l1 != null && l2 != null) {
ListNode listNode = new ListNode(0);

tempSum = l1.val + l2.val + 1;
} else {
tempSum = l1.val + l2.val;
}

if (tempSum >= 10) {
listNode.val = tempSum % 10;
} else {
listNode.val = tempSum;
}

l1 = l1.next;
l2 = l2.next;
}

while (l1 != null) {
ListNode listNode = new ListNode(0);

tempSum = l1.val + 1;
} else {
tempSum = l1.val;
}

if (tempSum >= 10) {
listNode.val = tempSum % 10;
} else {
listNode.val = tempSum;
}

l1 = l1.next;
}

while (l2 != null) {
ListNode listNode = new ListNode(0);
tempSum = l2.val + 1;
} else {
tempSum = l2.val;
}

if (tempSum >= 10) {
listNode.val = tempSum % 10;
} else {
listNode.val = tempSum;
}

l2 = l2.next;
}

ListNode listNode = new ListNode(1);
}

return l3.next;
}
``````

``````    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
int carry = 0;

while (l1 != null || l2 != null) {
int d1 = l1 == null ? 0 : l1.val;
int d2 = l2 == null ? 0 : l2.val;
int sum = d1 + d2 + carry;
carry = sum >= 10 ? 1 : 0;
cur.next = new ListNode(sum % 10);
cur = cur.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
if (carry == 1) cur.next = new ListNode(1);

return dummy.next;
}
``````