| | 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 | | namespace LeetCode.Algorithms.AddToArrayFormOfInteger; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class AddToArrayFormOfIntegerSummation : IAddToArrayFormOfInteger |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(max(n, log k)), where n is the length of the array num and log k is the number of digits |
| | 19 | | /// integer k |
| | 20 | | /// Space complexity - O(max(n, log k)), where n is the length of the array num and log k is the number of digit |
| | 21 | | /// the integer k |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="num"></param> |
| | 24 | | /// <param name="k"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public IList<int> AddToArrayForm(int[] num, int k) |
| 3 | 27 | | { |
| 3 | 28 | | var result = new List<int>(); |
| | 29 | |
|
| 3 | 30 | | var kString = k.ToString(); |
| 3 | 31 | | var kIndex = kString.Length - 1; |
| 3 | 32 | | var numIndex = num.Length - 1; |
| | 33 | |
|
| 3 | 34 | | var carry = 0; |
| | 35 | |
|
| 13 | 36 | | while (numIndex >= 0 || kIndex >= 0) |
| 10 | 37 | | { |
| 10 | 38 | | var val1 = 0; |
| | 39 | |
|
| 10 | 40 | | if (numIndex >= 0) |
| 10 | 41 | | { |
| 10 | 42 | | val1 = num[numIndex]; |
| 10 | 43 | | numIndex--; |
| 10 | 44 | | } |
| | 45 | |
|
| 10 | 46 | | var val2 = 0; |
| | 47 | |
|
| 10 | 48 | | if (kIndex >= 0) |
| 8 | 49 | | { |
| 8 | 50 | | val2 = (int)char.GetNumericValue(kString[kIndex]); |
| 8 | 51 | | kIndex--; |
| 8 | 52 | | } |
| | 53 | |
|
| 10 | 54 | | var sum = val1 + val2 + carry; |
| | 55 | |
|
| 10 | 56 | | if (sum >= 10) |
| 3 | 57 | | { |
| 3 | 58 | | sum -= 10; |
| 3 | 59 | | carry = 1; |
| 3 | 60 | | } |
| | 61 | | else |
| 7 | 62 | | { |
| 7 | 63 | | carry = 0; |
| 7 | 64 | | } |
| | 65 | |
|
| 10 | 66 | | result.Add(sum); |
| 10 | 67 | | } |
| | 68 | |
|
| 3 | 69 | | if (carry > 0) |
| 1 | 70 | | { |
| 1 | 71 | | result.Add(carry); |
| 1 | 72 | | } |
| | 73 | |
|
| 3 | 74 | | result.Reverse(); |
| | 75 | |
|
| 3 | 76 | | return result; |
| 3 | 77 | | } |
| | 78 | | } |