개발하는 사막여우
개발하는 사막여우
개발하는 사막여우
전체 방문자
오늘
어제
  • All (310)
    • Books (13)
      • 읽기 좋은 코드가 좋은 코드다 (13)
    • Study (6)
      • Blockchain (3)
      • Algorithm (3)
    • Baekjoon (36)
    • Programmers (166)
    • LeetCode (15)
    • Open Source (1)
      • Youtube Popout Player (1)
    • Language (32)
      • Python (9)
      • JS (8)
      • Java (5)
      • HTML (6)
      • CSS (4)
    • Library & Framework (15)
      • React.js (15)
    • IDE (2)
      • IntelliJ (2)
    • Airdrop (9)
    • Tistory (2)
    • etc.. (12)
      • Cozubi (6)
      • lol-chess (0)

블로그 메뉴

  • Github

공지사항

인기 글

태그

  • 프로그래머스
  • 카카오 공채
  • 코인줍줍
  • 클린 코드
  • 코주비
  • 카카오 알고리즘 문제
  • 백준
  • 클린 코드 작성법
  • 카카오 코딩테스트
  • programmers
  • 파이썬
  • 읽기 좋은 코드가 좋은 코드다
  • Java
  • 코딩테스트연습
  • 알고리즘문제풀이
  • 신규 코인 에어드랍
  • 2018 KAKAO BLIND RECRUITMENT
  • Cozubi
  • 프로그래머스 위클리 챌린지
  • Python

최근 댓글

최근 글

티스토리

반응형
hELLO · Designed By 정상우.
개발하는 사막여우

개발하는 사막여우

[리트코드] 2. Add Two Numbers / Javascript
LeetCode

[리트코드] 2. Add Two Numbers / Javascript

2021. 9. 9. 17:36
반응형

문제주소 :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


<문제 설명>

더보기

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.

 

<풀이법>

▒ 한줄 개념: 연결리스트 ▒ 

문제 설명을 읽어보면 처음엔 무슨 소리인가 쉽지만, 굉장히 단순한 문제입니다.

두 개의 정수가 역순으로 연결리스트로 구현되어 있습니다.

ex) 435: 5 -> 3 -> 4
ex) 342: 2 -> 4 -> 3
ex) 456: 6 -> 5 -> 4

이런 규칙의 연결리스트 두 개를 받았을 때, 원래 두 정수의 합을 다시 연결리스트로 반환하는 문제입니다.

 

어차피 각 정수가 역순으로 되어있기 때문에, 리스트를 순서대로 타고 가면 일의 자리부터 접근할 수 있다는 뜻이 됩니다. 따라서, 두 리스트를 단순하게 앞에서부터 접근하면서 더해주는 식으로 새로운 리스트를 만들면, 그게 정답이 됩니다. 중간에 올림 처리만 반복문을 진행하는 과정에서 해주면, 쉽게 풀 수 있습니다.

l1        = 2    -> 4     -> 3
l2        = 6    -> 5     -> 4
answer = 2+6 -> 4+5 -> 3+4
          = 8     -> 9     -> 7

 

<코드(Javascript)>

/**
 * 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) {
    const answer = new ListNode();
    let n1 = l1;
    let n2 = l2;
    let cur = answer;
    let carry = false;
    
    let val = n1.val + n2.val;
    if(val > 9){
        carry = true;
        val = val % 10;
    }
    cur.val = val;
    
    while(n1.next || n2.next){
        n1 = n1.next || new ListNode();
        n2 = n2.next || new ListNode();
        cur.next = new ListNode();
        cur = cur.next;
        val = n1.val + n2.val;
        if(carry){
            val++;
            carry = false;
        }
        if(val > 9){
            carry = true;
            val = val % 10;
        }
        cur.val = val;
    }
    if(carry){
        cur.next = new ListNode(1);
    }
    
    return answer;
};

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

 

 

더 많은 코드 보기(GitHub) : github.com/dwkim-97/CodingTest

 

 

반응형
저작자표시 (새창열림)

'LeetCode' 카테고리의 다른 글

[리트코드] 336. Palindrome Pairs / Javascript  (0) 2021.09.15
[리트코드] 5. Longest Palindromic Substring / Javascript  (0) 2021.09.09
[리트코드] 1130. Minimum Cost Tree From Leaf Values / Javascript  (0) 2021.09.08
[리트코드] 1647. Minimum Deletions to Make Character Frequencies Unique / Javascript  (0) 2021.09.08
[리트코드] 6. ZigZag Conversion / Javascript  (0) 2021.09.07
    'LeetCode' 카테고리의 다른 글
    • [리트코드] 336. Palindrome Pairs / Javascript
    • [리트코드] 5. Longest Palindromic Substring / Javascript
    • [리트코드] 1130. Minimum Cost Tree From Leaf Values / Javascript
    • [리트코드] 1647. Minimum Deletions to Make Character Frequencies Unique / Javascript
    개발하는 사막여우
    개발하는 사막여우
    개발개발 주저리주저리

    티스토리툴바