알고리즘/문제

[LeetCode] - M - Add Two Numbers

Casteira 2023. 8. 29. 00:59

https://leetcode.com/problems/add-two-numbers/description/?envType=study-plan-v2&envId=top-interview-150

 

Add Two Numbers - LeetCode

Can you solve this real interview question? Add Two Numbers - 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

leetcode.com

 

📌 - 풀이

노드를 사용한 문제를 LeetCode에서 처음 접해봐서 익숙하지 않지만 이번 문제는 그렇게 복잡하진 않았던 것 같다.

 

  1. li1과 li2가 null이 아닐 때 li1과 li2를 하나씩 증가시키면서 해당 val 값을 더하고
  2. 더한 값이 10을 넘지 않으면 더한 결과 값으로 listNode를 하나씩 생성
  3. 10이 넘으면 roundUp으로 다음 숫자에 roundUp만큼 sum에 추가해서 ListNode를 생성

return으로 answer.next를 하는 것도 익숙치 않고, node를 코테에서 다루는게 신기했다.

 

몇 문제 더 풀어봐야 감을 잡을 수 있을 듯

 

🔥 - Java 코드

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode listNode = new ListNode();
        ListNode answer = listNode;
        int roundUp = 0;

        while (l1 != null || l2 != null) {
            int sum = roundUp;

            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }

            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }

            roundUp = sum / 10;
            sum %= 10;

            listNode.next = new ListNode(sum);
            listNode = listNode.next;
        }

        if (roundUp > 0) {
            listNode.next = new ListNode(roundUp);
        }
        return answer.next;
    }
    
}