| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using LeetCode.Core.Models; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.AddTwoNumbers; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class AddTwoNumbersIterative : IAddTwoNumbers |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n + m), where n is the length of the list l1 and m is the length of the list l2 |
| | 21 | | /// Space complexity - O(max(n, m)), where n is the length of the list l1 and m is the length of the list l2 |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="l1"></param> |
| | 24 | | /// <param name="l2"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public ListNode? AddTwoNumbers(ListNode? l1, ListNode? l2) |
| 4 | 27 | | { |
| 4 | 28 | | var dummyHead = new ListNode(); |
| 4 | 29 | | var current = dummyHead; |
| 4 | 30 | | var carry = 0; |
| | 31 | |
|
| 27 | 32 | | while (l1 != null || l2 != null || carry != 0) |
| 23 | 33 | | { |
| 23 | 34 | | var sum = carry; |
| | 35 | |
|
| 23 | 36 | | if (l1 != null) |
| 12 | 37 | | { |
| 12 | 38 | | sum += l1.val; |
| 12 | 39 | | l1 = l1.next; |
| 12 | 40 | | } |
| | 41 | |
|
| 23 | 42 | | if (l2 != null) |
| 18 | 43 | | { |
| 18 | 44 | | sum += l2.val; |
| 18 | 45 | | l2 = l2.next; |
| 18 | 46 | | } |
| | 47 | |
|
| 23 | 48 | | carry = sum / 10; |
| 23 | 49 | | current.next = new ListNode(sum % 10); |
| 23 | 50 | | current = current.next; |
| 23 | 51 | | } |
| | 52 | |
|
| 4 | 53 | | return dummyHead.next; |
| 4 | 54 | | } |
| | 55 | | } |