728x90
https://leetcode.com/problems/add-two-numbers/description/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
var head = new ListNode();
var current = head;
bool carry = false;
while (((l1 != null) || (l2 != null)) || carry)
{
int sum = 0;
if (carry)
{
++sum;
carry = false;
}
if (l1 != null)
{
sum += l1.val;
l1 = l1.next;
}
if (l2 != null)
{
sum += l2.val;
l2 = l2.next;
}
if (sum >= 10)
{
sum %= 10;
carry = true;
}
current.next = new ListNode(sum);
current = current.next;
}
return head.next;
}
}
728x90
'Programing > Algorithm' 카테고리의 다른 글
[LeetCode] 6. Zigzag Conversion (0) | 2025.02.07 |
---|---|
[LeetCode] 5. Longest Palindromic Substring (0) | 2025.02.07 |
[LeetCode] 4. Median of Two Sorted Arrays (0) | 2025.01.21 |
[LeetCode] 3. Longest Substring Without Repeating Characters (0) | 2025.01.20 |
[LeetCode] 1. Two Sum (0) | 2025.01.20 |