兩數(shù)相加
給出兩個 非空 的鏈表用來表示兩個非負的整數(shù)。其中,它們各自的位數(shù)是按照 逆序 的方式存儲的迹冤,并且它們的每個節(jié)點只能存儲 一位 數(shù)字匿垄。
如果移宅,我們將這兩個數(shù)相加起來,則會返回一個新的鏈表來表示它們的和椿疗。
您可以假設(shè)除了數(shù)字 0 之外漏峰,這兩個數(shù)都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-two-numbers
思路:
分2種情況:
1.鏈表長度相等
2.鏈表長度不相等
解答 :
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let p1 = l1;
let p2 = l2;
let result =[]
let addition = 0;
while(p1!=null&&p2!=null)
{
let sum = p1.val+p2.val+addition;
addition = 0;
p1=p1.next;
p2=p2.next;
if(sum>=10)
{
addition =1;
}
result.push(sum%10);
}
/*鏈表長度相等*/
if(p1===null&&p2===null)
{
if(addition>0)
{
result.push(1);
}
}
/*鏈表長度不相等*/
if(p1!=null)
{
while(p1!=null)
{
if(p1.val+addition>=10)
{
result.push((p1.val+addition)%10);
addition = 1;
}
else
{
result.push((p1.val+addition)%10);
addition = 0;
}
p1 = p1.next;
}
if(addition>0)
{
result.push(1);
}
}
if(p2!=null)
{
while(p2!=null)
{
if(p2.val+addition>=10)
{
result.push((p2.val+addition)%10);
addition = 1;
}
else
{
result.push((p2.val+addition)%10);
addition = 0;
}
p2= p2.next;
}
if(addition>0)
{
result.push(1);
}
}
let resultList = buildNode(result);
return resultList.next;
};
var buildNode = function(vals)
{
let numNodeHead = new ListNode(vals.length);
let pHead = numNodeHead;
for(let id=0;id<vals.length;++id)
{
let val = vals[id];
let numNode = new ListNode(val);
numNodeHead.next=numNode;
numNodeHead =numNodeHead.next;
}
return pHead
}