> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/01-18-2022-2.md).

# 01/18/2022 2

Add two numbers

![](https://423021406-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Mjjyb1BqScHCWaFFmF4%2Fuploads%2FjVG8DiUUP7ZL5ESNYeO4%2Fimage.png?alt=media\&token=8f738092-7086-4064-8573-c949ed02986a)

* Initialize current node to dummy head of the returning list.
* Initialize carry to 0
* Loop through lists l1 and l2 until you reach both ends.
  * Set x to node l1's value. If l1 has reached the end of l1, set to 0.
  * Set y to node l2s value. If l2 has reached the end of l2, set to 0.
  * Set sum = x + y + carry
  * Update carry = sum / 10
  * Create a new node with the digit value of (sum mod 10) and set it to current node's next, then advance current node to next.
  * Advance both l1 and l2.
* Check if carry = 1, if so append a new node with digit 1 to the returning list.
* Return dummy head's next node
* Time O(max(m,n))
* Space O(max(m,n))

```
class Solution {
    
    int carry = 0;
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
        if (l1 == null && l2 == null && carry == 0) {
            return null;
        }
        
        int val1 = l1 == null ? 0 : l1.val;
        int val2 = l2 == null ? 0 : l2.val;
        
        int sum = val1 + val2 + carry;
        carry = sum/10;
        
        l1 = l1 == null ? null : l1.next;
        l2 = l2 == null ? null : l2.next;
        
        ListNode ans = new ListNode(sum%10, addTwoNumbers(l1, l2));
        
        return ans;
    }
}
```
