# LeetCode刷题日志#2：两数相加

## 容易想到的解法

``````/**
* function ListNode(val) {
*     this.val = val;
*     this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
const arr3 = [];

const len = Math.max(arr1.length, arr2.length);
let flag = 0;

for (let i = 0; i < len || flag; i += 1) {
const byte1 = arr1[i] || 0;
const byte2 = arr2[i] || 0;
const byte3 = byte1 + byte2 + flag;
if (byte3 >= 10) {
arr3.push(byte3 - 10);
flag = 1;
} else {
arr3.push(byte3);
flag = 0;
}
}

};

const arr = [];
while(pointer) {
arr.push(pointer.val);
pointer = pointer.next;
}
return arr;
}
arr.forEach((item, index) => {
pointer.val = item;
if (index === arr.length - 1) {
pointer.next = null;
} else {
pointer.next = {};
pointer = pointer.next;
}
});

}``````

## 最优解

``````/**
* function ListNode(val) {
*     this.val = val;
*     this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let pointer1 = l1;
let pointer2 = l2;
let flag = 0;

while(typeof pointer1.val === 'number' || typeof pointer2.val === 'number' || flag) {
if (pointer1.val === undefined) {
pointer1.val = 0;
}
if (pointer2.val === undefined) {
pointer2.val = 0;
}

pointer1.val = pointer1.val + pointer2.val + flag;
if (pointer1.val >= 10) {
pointer1.val = pointer1.val - 10;
flag = 1;
} else {
flag = 0;
}

if (!pointer1.next && !pointer2.next && !flag) {
return l1;
}

if (!pointer1.next) {
pointer1.next = {};
}
pointer1 = pointer1.next;
if (!pointer2.next) {
pointer2.next = {};
}
pointer2 = pointer2.next;
}

return l1;
};``````