---
# System prepended metadata

title: 2. Add Two Numbers (Medium)
tags: [LeetCode]

---

---
tags: LeetCode
---

# 2. Add Two Numbers (Medium)
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 contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do **not contain any leading zero**, except the number 0 itself.

Example:    
```
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)    
Output: 7 -> 0 -> 8    
Explanation: 342 + 465 = 807.    
```
---

輸入範本如下
```C#
public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        
    }
}
```

### 直覺想法
跟字串相加的題目[415. Add Strings](https://hackmd.io/7bHRBu0JQjGZ_k_psqaJEg?view#415-Add-Strings)很類似 , 只是儲存實體改成 LinkList 而已 , 把 code 複製過來改就好 , 算簡單的.
反正核心概念就一個一個加 , 需要紀錄 carry , 以及需要多一個 LinkList 的操作. 

```C#
92 ms	27.6 MB
You are here!
Your runtime beats 99.85 % of csharp submissions.
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
    ListNode listNode = new ListNode(-1); // init & 指向初始位置.
    ListNode point = listNode; // 使用 point 指向目前 listNode 計算的位置
    int carry = 0;
    while (l1 != null || l2 != null || carry == 1) // 當 l1 or l2 未走訪完 , 或是尚有進位數字 carry 則繼續計算.
    {
        int sum = carry;
        if (l1 != null) sum += l1.val;
        if (l2 != null) sum += l2.val;
        point.next = new ListNode(sum % 10);
        point = point.next;
        carry = sum >= 10 ? 1 : 0;
        l1 = l1?.next; // 若 l1 為 null 則回傳 null
        l2 = l2?.next; // 若 l2 為 null 則回傳 null
    }
    return listNode.next;
}
```








### Thank you! 

You can find me on

- [GitHub](https://github.com/s0920832252)
- [Facebook](https://www.facebook.com/fourtune.chen)

若有謬誤 , 煩請告知 , 新手發帖請多包涵

# :100: :muscle: :tada: :sheep: 
