두 연결리스트를 가지고 합을 계산해야 한다.
일종의 후위표기법이다. [2, 4, 3], [5, 6, 4] 이렇게 주어졌을 때 342 + 465 = 807이 되어 결과는 [7, 0, 8]이 정답이 된다.
길이가 다른 경우도 생각해 보자.
[2, 4, 3], [5, 7]이다. 이러면 342 + 75 = 417이 되고 [7, 1, 4]가 정답이 된다.
우선 자리 올림수(carry)가 발생한 경우를 생각해야 한다.
- 두 연결리스트에서 값을 꺼낸다
- 값을 더해 노드를 만든다.
- 이때 캐리가 발생했다면 다음에 더하기 위해 기록해 둔다.
- 캐리는 합을 10으로 나눈 몫이고 자릿수는 합을 10으로 나눈 나머지이다.
- 반복이 끝났을 때 캐리가 남아있다면 추가해 준다.
/**
* 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 head = new ListNode();
ListNode curr = head;
int carry = 0;
while (l1 != null || l2 != null) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
carry = sum / 10;
ListNode node = new ListNode(sum % 10);
curr.next = node;
curr = curr.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return head.next;
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
| LeetCode 130 - Surrounded Regions (0) | 2024.10.22 |
|---|---|
| LeetCode 433 - Minimum Genetic Mutation (0) | 2024.10.22 |
| LeetCode 637 - Average of Levels in Binary Tree (0) | 2024.10.21 |
| LeetCode 230 - Kth Smallest Element in a BST (0) | 2024.10.21 |
| LeetCode 11053 - 가장 긴 증가하는 부분 수열 (0) | 2024.10.18 |