2.两数相加
class ListNode {
constructor(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
}
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let p1=l1
let p2=l2
let arr=[]
let carry=0 // 进位
while(p1||p2){
let current1=p1?p1.val:0
let current2=p2?p2.val:0
let sun=current1+current2+carry
carry=Math.floor(sun/10)
arr.push(sun%10)
if(p1)p1=p1.next
if(p2)p2=p2.next
}
if(carry)arr.push(carry)
return buildLinkedList(arr)
};
// up time:6ms space:56mb
// 4ms 56mb
var addTwoNumbersSimple = function(l1, l2) {
let head = new ListNode(0)
let p1=l1
let p2=l2
let p3=head
let carry=0 // 进位
while(p1||p2){
let current1=p1?p1.val:0
let current2=p2?p2.val:0
let sun=current1+current2+carry
carry=Math.floor(sun/10)
p3.next=new ListNode(sun%10)
if(p1)p1=p1.next
if(p2)p2=p2.next
p3=p3.next
}
// 处理最高位
if(carry) p3.next=new ListNode(carry)
return head.next
};
let a1 = [9,9,9,9,9,9,9], a2 = [9,9,9,9]
let l1= buildLinkedList(a1);
let l2= buildLinkedList(a2);
console.log(addTwoNumbers(l1, l2));
function buildLinkedList(arr) {
let head = new ListNode(0);
let p = head;
for (let i = 0; i < arr.length; i++) {
p.next = new ListNode(arr[i]);
p = p.next;
}
return head.next;
}
'
标签:p2,p1,ListNode,相加,next,let,carry,两数 From: https://www.cnblogs.com/KooTeam/p/18664512