| | 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.SumOfDigitsOfStringAfterConvert; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SumOfDigitsOfStringAfterConvertIterative : ISumOfDigitsOfStringAfterConvert |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int GetLucky(string s, int k) |
| 9 | 25 | | { |
| 9 | 26 | | var sum = 0; |
| | 27 | |
|
| 931 | 28 | | foreach (var c in s) |
| 452 | 29 | | { |
| 452 | 30 | | var number = c - 'a' + 1; |
| | 31 | |
|
| 1232 | 32 | | while (number > 0) |
| 780 | 33 | | { |
| 780 | 34 | | sum += number % 10; |
| | 35 | |
|
| 780 | 36 | | number /= 10; |
| 780 | 37 | | } |
| 452 | 38 | | } |
| | 39 | |
|
| 27 | 40 | | while (k > 1) |
| 18 | 41 | | { |
| 18 | 42 | | var currentSum = 0; |
| | 43 | |
|
| 50 | 44 | | while (sum > 0) |
| 32 | 45 | | { |
| 32 | 46 | | currentSum += sum % 10; |
| | 47 | |
|
| 32 | 48 | | sum /= 10; |
| 32 | 49 | | } |
| | 50 | |
|
| 18 | 51 | | sum = currentSum; |
| | 52 | |
|
| 18 | 53 | | k--; |
| 18 | 54 | | } |
| | 55 | |
|
| 9 | 56 | | return sum; |
| 9 | 57 | | } |
| | 58 | | } |