Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- trim
- es7
- 카카오톡채널
- es6
- 오픈채팅
- 함수
- callbackhell
- JavaScript
- 유사배열객체
- 오픈빌더
- 콜백함수
- callback
- expo
- closure
- 객체
- developers
- arguments
- 자바스크립트
- 챗봇
- 자연어처리
- vuejs
- 배열
- async
- await
- Promise
- 변수
- 순수함수
- ReactNative
- 플러스친구
- 카카오
Archives
- Today
- Total
말랑말랑 LAB
leetcode#2 Add Two Numbers 본문
Question
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0] Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]
Constraints:
- The number of nodes in each linked list is in the range [1, 100].
- 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
solution
var addTwoNumbers = function(l1, l2) {
var result = [];
var l1_len = l1.length;
var l2_len = l2.length;
var len = l1_len >= l2_len ? l1_len : l2_len;
var sumValue = 0;
var overCnt = 0;
for(var i=0; i<len; i++) {
if(l1[i] === undefined) l1[i] = 0;
if(l2[i] === undefined) l2[i] = 0;
sumValue = l1[i] + l2[i] + overCnt;
if(sumValue >= 10) {
sumValue = sumValue % 10;
overCnt = 1;
result.push(sumValue);
if (i === len-1) {
result.push(1);
}
} else {
overCnt = 0;
result.push(sumValue);
}
}
return result;
};
other solution
var addTwoNumbers = function(l1, l2) {
let newNode = new ListNode(0);
let head = newNode
var carry = false
while(l1 || l2){
var nodeSum = (l1?.val || 0) + (l2?.val || 0);
nodeSum += (carry) ? 1 : 0;
if(nodeSum > 9){
carry = true
}else{
carry = false
}
head.next = new ListNode(nodeSum % 10)
if(l1)l1 = l1.next;
if(l2)l2 = l2.next;
head = head.next
}
if(carry){
head.next = new ListNode(carry);
}
return newNode.next
};
'JavaScript > Algorithm' 카테고리의 다른 글
leetcode#73 Set Matrix Zeroes (0) | 2021.08.21 |
---|---|
[프로그래머스 알고리즘] Level 2 124 나라의 숫자 (0) | 2018.12.28 |
[프로그래머스 알고리즘] Level 1 수박수박수박 문제 (0) | 2018.12.16 |
Comments