| | | 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 | | using System.Text; |
| | | 13 | | |
| | | 14 | | namespace LeetCode.Algorithms.AddStrings; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public sealed class AddStringsIterative : IAddStrings |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Time complexity - O(max(n, m)) |
| | | 21 | | /// Space complexity - O(max(n, m)) |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="num1"></param> |
| | | 24 | | /// <param name="num2"></param> |
| | | 25 | | /// <returns></returns> |
| | | 26 | | public string AddStrings(string num1, string num2) |
| | 4 | 27 | | { |
| | 4 | 28 | | var resultBuilder = new StringBuilder(); |
| | | 29 | | |
| | 4 | 30 | | var num1Index = num1.Length - 1; |
| | 4 | 31 | | var num2Index = num2.Length - 1; |
| | | 32 | | |
| | 4 | 33 | | var carry = 0; |
| | | 34 | | |
| | 30 | 35 | | while (num1Index >= 0 || num2Index >= 0) |
| | 26 | 36 | | { |
| | 26 | 37 | | var val1 = 0; |
| | 26 | 38 | | var val2 = 0; |
| | | 39 | | |
| | 26 | 40 | | if (num1Index >= 0) |
| | 25 | 41 | | { |
| | 25 | 42 | | val1 = (int)char.GetNumericValue(num1[num1Index]); |
| | 25 | 43 | | num1Index--; |
| | 25 | 44 | | } |
| | | 45 | | |
| | 26 | 46 | | if (num2Index >= 0) |
| | 25 | 47 | | { |
| | 25 | 48 | | val2 = (int)char.GetNumericValue(num2[num2Index]); |
| | 25 | 49 | | num2Index--; |
| | 25 | 50 | | } |
| | | 51 | | |
| | 26 | 52 | | var sum = val1 + val2 + carry; |
| | | 53 | | |
| | 26 | 54 | | if (sum >= 10) |
| | 12 | 55 | | { |
| | 12 | 56 | | sum -= 10; |
| | 12 | 57 | | carry = 1; |
| | 12 | 58 | | } |
| | | 59 | | else |
| | 14 | 60 | | { |
| | 14 | 61 | | carry = 0; |
| | 14 | 62 | | } |
| | | 63 | | |
| | 26 | 64 | | resultBuilder.Insert(0, sum); |
| | 26 | 65 | | } |
| | | 66 | | |
| | 4 | 67 | | if (carry > 0) |
| | 1 | 68 | | { |
| | 1 | 69 | | resultBuilder.Insert(0, carry); |
| | 1 | 70 | | } |
| | | 71 | | |
| | 4 | 72 | | return resultBuilder.ToString(); |
| | 4 | 73 | | } |
| | | 74 | | } |