| | 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 AddTwoNumbersInPlaceCarry : 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 carry = 0; |
| | 29 | |
|
| 4 | 30 | | ListNode? head = null; |
| | 31 | |
|
| 25 | 32 | | while (l1 != null || l2 != null) |
| 21 | 33 | | { |
| 21 | 34 | | var val1 = l1?.val ?? 0; |
| 21 | 35 | | var val2 = l2?.val ?? 0; |
| | 36 | |
|
| 21 | 37 | | var sum = val1 + val2 + carry; |
| | 38 | |
|
| 21 | 39 | | carry = 0; |
| | 40 | |
|
| 21 | 41 | | if (sum >= 10) |
| 18 | 42 | | { |
| 18 | 43 | | carry = 1; |
| 18 | 44 | | sum -= 10; |
| 18 | 45 | | } |
| | 46 | |
|
| 21 | 47 | | l1 = l1?.next; |
| 21 | 48 | | l2 = l2?.next; |
| | 49 | |
|
| 21 | 50 | | head = new ListNode(sum, head); |
| 21 | 51 | | } |
| | 52 | |
|
| 4 | 53 | | if (carry > 0) |
| 2 | 54 | | { |
| 2 | 55 | | head = new ListNode(1, head); |
| 2 | 56 | | } |
| | 57 | |
|
| 4 | 58 | | return Reverse(head); |
| 4 | 59 | | } |
| | 60 | |
|
| | 61 | | private static ListNode? Reverse(ListNode? head) |
| 4 | 62 | | { |
| 4 | 63 | | ListNode? prev = null; |
| 4 | 64 | | var current = head; |
| | 65 | |
|
| 27 | 66 | | while (current != null) |
| 23 | 67 | | { |
| 23 | 68 | | var next = current.next; |
| 23 | 69 | | current.next = prev; |
| 23 | 70 | | prev = current; |
| 23 | 71 | | current = next; |
| 23 | 72 | | } |
| | 73 | |
|
| 4 | 74 | | return prev; |
| 4 | 75 | | } |
| | 76 | | } |