📌 문제
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.
📌 방법
1️⃣ ListNode를 초기화
2️⃣ 결과를 반환할 값에 node를 대입
3️⃣ 반복문을 돌며 각 ListNode의 val를 더함
4️⃣ 나머지와 나누는 이유 = 합이 두 자리수가 될 수 있기 때문 (10 이상)
한 자리수 이상이면, 일의 자리 수가 값이 되고 십의 자리수의 값 만큼 다음에 더해줘야 함.
5️⃣ 반복문의 조건식이 참인 동안 반복
6️⃣ 결과 반환
/**
* 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) {
/*
* l1 = [2,4,3]
* l2 = [5,6,4]
* result = [7,0,8]
*/
ListNode node = new ListNode(0);
ListNode result = node;
int sum = 0;
while(l1 != null || l2 != null || sum > 0) {
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
node.next = new ListNode(sum % 10);
sum /= 10;
node = node.next;
}
return result.next;
}
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode]006. Zigzag Conversion JAVA (0) | 2022.12.21 |
---|---|
[LeetCode]007. Reverse Integer JAVA (0) | 2022.12.19 |
[LeetCode]005. Longest Palindromic Substring JAVA (0) | 2022.12.19 |
[LeetCode] 003. Longest Substring Without Repeating Characters JAVA (0) | 2022.12.16 |
[LeetCode] 001. Two Sum JAVA (0) | 2022.12.15 |
댓글