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 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
My code:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let resultArr = [], num1 = "", num2 = "";
while(l1!= null) { // convert to number string
num1 += l1.val;
l1 = l1.next;
}
while(l2!= null){
num2 += l2.val;
l2 = l2.next;
}
num1 = num1.split("").reverse().join(""); // convert to normal order
num2 = num2.split("").reverse().join("");
sum = (+num1) + (+num2);
resultArr = sum.toString().split("").reverse();
let newListNode = new ListNode(0);
let head = newListNode;
for(let i = 0; i < resultArr.length; i++) { // add to new ListNode
head.next = new ListNode(+resultArr[i]);
head = head.next;
}
return newListNode.next;
};
Note:
原本没理解到位,看到testcase那里的input是数组就按照数组的思路去写了,写完run了才发现什么结果都没有,才按照链表的思路重新写,感觉给出的testcase有点误导 = =
思路是先把两个逆序的加数转换为正序,再进行相加,得到的和再转换为逆序由链表连接每一位数,思路是这样子没错,代码写好了submit的时候发现有一个测试用例通不过:
太大的数用我的思路会被转换为科学计数形式导致无法满足题目条件(哭笑
于是决定顺着给出的链表形式,从个位数一直加到最后一位,每加一位处理进位,同时判断两个链表是否在当前位都有值,在计算完一位以后就把当前位添加到返回的链表的next
My code:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
var carry = 0;
var resultListNode = new ListNode(0);
var head = resultListNode;
while(l1 || l2 || carry) {
var sum = 0;
if(l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if(l2 != null) {
sum += l2.val;
l2 = l2.next;
}
sum += carry;
carry = parseInt(sum / 10); // carry must be int
head.next = new ListNode(sum % 10);
head = head.next;
}
return resultListNode.next;
};
Result:
其中需要注意的是,计算进位的表达式开始写成carry = sum / 10;
导致结果是这样的:
仔细检查才发现这个问题,弱类型语言容易忘记数据类型导致不必要的错误,需要检讨检讨……