---
title: 'LeetCode 2. Add Two Numbers'
disqus: hackmd
---
# LeetCode 2. Add Two Numbers
## Description
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
## Example
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
## Constraints
* The number of nodes in each linked list is in the range [1, 100].
* 0 <= Node.val <= 9
* It is guaranteed that the list represents a number that does not have leading zeros.
## Answer
此題只要將list中每位數的val抓出來相加並藉由add來考慮進位的問題,其中相加後的值對10取餘數即可,而進位數就是取10的商,最後若有進位或是list還有數值就繼續往下開空間。list處理完之後就要判斷有無進位項並指向NULL結束程式。
```Cin=
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int add = 0, tmp = 0;
struct ListNode *ans = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *opr = ans;
while(l1 != NULL || l2 != NULL){
if(l1 != NULL && l2 != NULL){
opr->val = (l1->val + l2->val + add) % 10;
add = (l1->val + l2->val + add) / 10;
l1 = l1->next;
l2 = l2->next;
}
else if(l1 != NULL){
opr->val = (l1->val + add) % 10;
add = (l1->val + add) / 10;
l1 = l1->next;
}
else{
opr->val = (l2->val + add) % 10;
add = (l2->val + add) / 10;
l2 = l2->next;
}
if(add || l1 != NULL || l2 != NULL){
opr->next = (struct ListNode*)malloc(sizeof(struct ListNode));
opr = opr->next;
}
}
if(add){opr->val = 1;}
opr->next = NULL;
return ans;
}
```
## Link
https://leetcode.com/problems/add-two-numbers/
###### tags: `Leetcode`