-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.cs
38 lines (32 loc) · 1.17 KB
/
Solution2.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution2
{
/// <summary>
/// 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.
/// <a href="https://leetcode.com/problems/add-two-numbers/">See the problem</a>
/// </summary>
/// <remarks>Time complexity O(n)</remarks>
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
if (l1 == null || l2 == null)
return l1 ?? l2;
var temp = new ListNode(0);
var prev = temp;
int carry = 0;
while (l1 != null || l2 != null || carry != 0)
{
carry += l1 == null ? 0 : l1.val;
carry += l2 == null ? 0 : l2.val;
l1 = l1?.next;
l2 = l2?.next;
prev.next = new ListNode(carry % 10);
prev = prev.next;
carry /= 10;
}
return temp.next;
}
}