https://leetcode.com/problems/add-two-numbers/
Add Two Numbers - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
/**
* 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 over = 0;
let result = new ListNode();
let cur = result;
while(l1||l2||over){
let a = l1? l1.val : 0;
let b = l2? l2.val : 0;
let sum = 0;
if(a+b+over>=10){
sum = a+b+over -10;
over = 1;
}else{
sum = a+b+over;
over = 0;
}
let newNode = new ListNode(sum);
result.next = newNode;
result = newNode;
l1 = l1 ? l1.next : null;
l2 = l2 ? l2.next : null;
}
return cur.next;
};
1. 첫 노드의 값들을 더함.
2. 10보다 큰 경우 over를 설정하고 10을 뺀 값을 넣고, 아니면 그냥 더한 값을 넣음
3. l1,l2가 모두 진행할 것이 없고, Over값이 0인 경우에 종료
발상 자체는 쉬웠는데 링크드 리스트를 사용해야되는데
예제나 Input에 배열로 표시라 배열인줄 알고 풀다가 왜 l1.length가 undefined인지 고민했었다..
'Algorithm > LeetCode' 카테고리의 다른 글
| LeetCode - Two Sum II - Input Array Is Sorted (0) | 2022.01.16 |
|---|---|
| LeetCode - Two Sum (0) | 2022.01.16 |
| LeetCode - Triangle (0) | 2022.01.15 |
| LeetCode - Best Time to Buy and Sell Stock II (0) | 2022.01.15 |
| LeetCode - Jump Game II (0) | 2022.01.15 |
