| | | 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.HappyNumber; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class HappyNumberHashSetChars : IHappyNumber |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(log n) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="n"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public bool IsHappy(int n) |
| | 5 | 24 | | { |
| | 5 | 25 | | if (n == 1) |
| | 1 | 26 | | { |
| | 1 | 27 | | return true; |
| | | 28 | | } |
| | | 29 | | |
| | 4 | 30 | | var hashSet = new HashSet<int>(); |
| | | 31 | | |
| | 35 | 32 | | while (n > 1 && !hashSet.Contains(n)) |
| | 31 | 33 | | { |
| | 31 | 34 | | hashSet.Add(n); |
| | 91 | 35 | | n = n.ToString().Sum(c => (int)Math.Pow(char.GetNumericValue(c), 2)); |
| | 31 | 36 | | } |
| | | 37 | | |
| | 4 | 38 | | return n == 1; |
| | 5 | 39 | | } |
| | | 40 | | } |