-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.两数相���.js
43 lines (39 loc) · 879 Bytes
/
2.两数相���.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* @lc app=leetcode.cn id=2 lang=javascript
*
* [2] 两数相加
*/
// @lc code=start
/**
* 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 head, tail;
let carry = 0;
while(l1 || l2) {
const num1 = l1 ? l1.val : 0;
const num2 = l2 ? l2.val : 0;
const sum = num1 + num2 + carry;
if(!head) {
head = tail = new ListNode(sum % 10);
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = Math.floor(sum / 10);
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
if (carry > 0) tail.next = new ListNode(carry);
return head;
};
// @lc code=end