두 Linked List를 더해주는 문제다.
리스트가 integer 크기 제한보다 길 때도 있으므로 BigInt를 사용했다.
/**
* 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 l = '';
let ll = '';
while (l1) {
l = l1.val + l;
l1 = l1.next;
}
while (l2) {
ll = l2.val + ll;
l2 = l2.next;
}
const sum = BigInt(l) + BigInt(ll);
const sumArr = sum
.toString()
.split('')
.map((i) => parseInt(i));
let result;
for (const i in sumArr) {
result = new ListNode(sumArr[i], result);
}
return result;
};
'Web development > Algorithm' 카테고리의 다른 글
[LeetCode] 3Sum (javascript) (0) | 2021.06.08 |
---|---|
[LeetCode] 104. Maximum Depth of Binary Tree (javascript) (0) | 2021.05.31 |
[LeetCode] 200. Number of Islands (javascript) (0) | 2021.05.31 |
[LeetCode] 12. Integer to Roman (javascript) (0) | 2021.05.31 |
[LeetCode] 43. Multiply Strings (javascript) (0) | 2021.05.31 |
댓글