0 喜欢

【每日一题】算法之两数相加

admin
admin
2020-10-31 16:29:03 阅读 88

LeetCode地址

两数相加

算法难度

中等

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} */ var addTwoNumbers = function(l1, l2) { let m = 0 let n = 0 let res = null let temp = null while(l1 || l2 || m) { let a = l1 ? l1.val : 0 let b = l2 ? l2.val : 0 n = (a + b + m) % 10 if (!temp) { res = temp = new ListNode(n) } else { temp = (temp.next = new ListNode(n)) } m = ~~((a + b + m) / 10) l1 = l1 ? l1.next : null l2 = l2 ? l2.next : null } return res };

关于作者
admin
admin
admin@ifront.net
 获得点赞 37
 文章阅读量 8910