-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathadd-two-numbers.js
More file actions
52 lines (43 loc) · 838 Bytes
/
add-two-numbers.js
File metadata and controls
52 lines (43 loc) · 838 Bytes
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
43
44
45
46
47
48
49
50
51
52
// Source : https://leetcode.com/problems/add-two-numbers/
// Author : Han Zichi
// Date : 2015-08-12
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
var add = 0
, ans
, head;
while(l1 || l2) {
var a = l1 ? l1.val : 0
, b = l2 ? l2.val : 0;
var sum = a + b + add;
add = ~~(sum / 10);
var node = new ListNode(sum % 10);
if (!ans)
ans = head = node;
else {
head.next = node;
head = node;
}
if (l1)
l1 = l1.next;
if (l2)
l2 = l2.next;
}
if (add) {
var node = new ListNode(add);
head.next = node;
head = node;
}
return ans;
};