两数相加
js实现两数相加
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const addTwoNumbers = function(l1, l2) {
let s = n = new ListNode() // s 进行存储 n用于管理
let a = 0 // 进位
while(l1 || l2) {
let num1 = l1 ? l1.val : 0
let num2 = l2 ? l2.val : 0
let sum = num1 + num2 + a
a = Math.floor(sum/10)
n.next = new ListNode(sum % 10)
n = n.next
console.log(l1,l2)
if(l1) l1 = l1.next
if(l2) l2 = l2.next
}
if(a) {
n.next = new ListNode(a)
}
return s.next
};