-
[linked list] add two numbersAlgorithm/LeetCode 2025. 4. 20. 11:40
✅ Problem
https://leetcode.com/problems/add-two-numbers/description/
✅ Approach & Solution
방식) 반복문 사용
더보기- 반복문을 사용해 첫 번째 연결 리스트, 두 번째 연결 리스트, 자리올림수를 모두 처리할 때까지 반복
- dummyNode 생성하여 연결 리스트 구현 (null 확인 로직 줄이기 위함)
/** * 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 dummyNode = new ListNode(-1); ListNode root = dummyNode, tail = dummyNode; int sum; int carry = 0; // 자리올림수 int remainder; // 자리올림수 제외한 나머지 값 (노드에 저장될 값) while (l1 != null || l2 != null || carry != 0) { sum = 0; if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } remainder = (sum + carry) % 10; carry = (sum + carry) / 10; tail.next = new ListNode(remainder); tail = tail.next; } return root.next; } }
'Algorithm > LeetCode' 카테고리의 다른 글
[linked list] swap nodes in pairs (0) 2025.05.04 [linked list] reverse linked list (0) 2025.04.20 [hash] jewels and stones (0) 2025.04.08 [array] best time to buy and sell stock 2 (0) 2025.04.07 [array] maximum product subarray (0) 2025.04.06