124 - 2 两数相加
题目
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
解答
感觉是要我模拟一下按位的加法。。保留一个进位数什么的
看题解,似乎要另外设定一个答案的链表,还要有个指针来跟踪。
但我总觉得不用,把答案覆盖掉l1不就行了吗?但是没能写出来。。
var addTwoNumbers = function(l1, l2) {
let pre = new ListNode(0)
cur = pre
carry = 0
while (l1 || l2) {
let x = l1 ? l1.val : 0
let y = l2 ? l2.val : 0
let sum = x + y + carry
carry = ~~(sum / 10)
cur.next = new ListNode(sum % 10)
cur = cur.next
if (l1) {
l1 = l1.next
}
if (l2) {
l2 = l2.next
}
}
if (carry === 1) {
cur.next = new ListNode(carry)
}
return pre.next
};Runtime: 120 ms, faster than 44.26% of JavaScript online submissions for Add Two Numbers.
Memory Usage: 38.5 MB, less than 56.94% of JavaScript online submissions for Add Two Numbers.
看题解的时候发现,Math.floor()可以用~~()来代替,也不知道为啥,反正就能行。
Runtime: 88 ms, faster than 17.60% of Python3 online submissions for Add Two Numbers.
Memory Usage: 14.2 MB, less than 5.67% of Python3 online submissions for Add Two Numbers.
Runtime: 16 ms, faster than 20.80% of Go online submissions for Add Two Numbers.
Memory Usage: 5 MB, less than 51.22% of Go online submissions for Add Two Numbers.
go有个更加简洁的做法
https://leetcode.com/problems/add-two-numbers/discuss/307928/Go-Clear-Go-solution
不需要另外设立carry,只需全局留sum,carry值就是其除以10
Runtime: 8 ms, faster than 89.62% of Go online submissions for Add Two Numbers.
Memory Usage: 4.9 MB, less than 85.37% of Go online submissions for Add Two Numbers.
Last updated
Was this helpful?