Skip to content

Commit 7a1e96e

Browse files
committed
https://leetcode.com/problems/happy-number/
1 parent cb59e03 commit 7a1e96e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

EasyProblems/HappyNumber.cs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
namespace LeetCode.EasyProblems;
2+
3+
public class HappyNumber
4+
{
5+
public bool IsHappy(int n)
6+
{
7+
HashSet<int> visitedNumbers = new HashSet<int>();
8+
9+
while (n != 1)
10+
{
11+
// Detect cycle - if we've seen this number before
12+
if (!visitedNumbers.Add(n))
13+
return false;
14+
15+
n = SumOfSquares(n);
16+
}
17+
18+
return true;
19+
}
20+
21+
private static int SumOfSquares(int n)
22+
{
23+
int sum = 0;
24+
while (n > 0)
25+
{
26+
int digit = n % 10;
27+
sum += digit * digit;
28+
n /= 10; // Remove last digit
29+
}
30+
31+
return sum;
32+
}
33+
34+
[Test(Description = "https://leetcode.com/problems/happy-number/")]
35+
[Category("Easy")]
36+
[Category("LeetCode")]
37+
[Category("Happy Number")]
38+
[TestCaseSource(nameof(Input))]
39+
public void Test1((bool Output, int Input) item)
40+
{
41+
var response = IsHappy(item.Input);
42+
Assert.That(response, Is.EqualTo(item.Output));
43+
}
44+
45+
public static IEnumerable<(bool Output, int Input)> Input =>
46+
new List<(bool Output, int Input)>()
47+
{
48+
(true, 19),
49+
(false, 2),
50+
};
51+
}

0 commit comments

Comments
 (0)