-
Notifications
You must be signed in to change notification settings - Fork 0
/
202-HappyNumber.cs
40 lines (33 loc) · 1018 Bytes
/
202-HappyNumber.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//Problem: https://leetcode.com/problems/happy-number/
using System.Collections.Generic;
namespace LeetCode {
public partial class Solution {
public bool IsHappyTwoPointer(int n) {
int slow = n, fast = n;
do {
slow = FindSquares(slow);
fast = FindSquares(FindSquares(fast));
} while (slow != fast);
return slow == 1;
}
public bool IsHappyHashSet(int num)
{
var hashSet = new HashSet<int>();
while (!hashSet.Contains(num) && num != 1)
{
hashSet.Add(num);
num = FindSquares(num);
}
return num == 1;
}
public int FindSquares(int n) {
int sum = 0, digit;
while(n > 0) {
digit = n % 10;
sum += digit * digit;
n = n / 10;
}
return sum;
}
}
}