• 문제 링크
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
• 풀이 코드
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1), node = dummy;
int carry = 0;
while (l1 != null || l2 != null) {
node = node.next = new ListNode(carry);
if (l1 != null) {
node.val += l1.val;
l1 = l1.next;
}
if (l2 != null) {
node.val += l2.val;
l2 = l2.next;
}
carry = node.val / 10;
node.val = node.val % 10;
}
if (carry != 0) node.next = new ListNode(carry);
return dummy.next;
}
}
/*public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}*/'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 12. Integer to Roman - Java (0) | 2026.05.09 |
|---|---|
| [LeetCode] 11. Container With Most Water - Java (0) | 2026.05.08 |
| [LeetCode] 9. Palindrome Number - Java (0) | 2026.05.07 |
| [LeetCode] 3. Longest Substring Without Repeating Characters - Java (0) | 2026.05.06 |
| [LeetCode] 1. Two Sum - Java (0) | 2026.05.04 |
댓글