| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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 sealed class AddToArrayFormOfIntegerDivision : 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; |
| | 10 | 55 | | carry = sum / 10; |
| | 10 | 56 | | sum %= 10; |
| | | 57 | | |
| | 10 | 58 | | result.Add(sum); |
| | 10 | 59 | | } |
| | | 60 | | |
| | 3 | 61 | | if (carry > 0) |
| | 1 | 62 | | { |
| | 1 | 63 | | result.Add(carry); |
| | 1 | 64 | | } |
| | | 65 | | |
| | 3 | 66 | | result.Reverse(); |
| | | 67 | | |
| | 3 | 68 | | return result; |
| | 3 | 69 | | } |
| | | 70 | | } |