# C#LeetCode刷题之#202-快乐数（Happy Number）

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Input: 19

Output: true

Explanation:

```public class Program {

public static void Main(string[] args) {
int nums = 19;

var res = IsHappy(nums);
Console.WriteLine(res);

nums = 26;
res = IsHappy2(nums);
Console.WriteLine(res);

nums = 65;
res = IsHappy3(nums);
Console.WriteLine(res);

}

private static bool IsHappy(int n) {
//递归法
var set = new HashSet<int>();
return ComputerHappy(n, set);
}

private static bool ComputerHappy(int n, HashSet<int> set) {
if(n == 1) return true;
if(set.Contains(n)) return false;
//计算各位数平方和
//int sum = 0;
//for(int i = 0; i < n.ToString().Length; i++) {
//    sum += (int)Math.Pow(n / (int)Math.Pow(10, i) % 10, 2);
//}
return ComputerHappy(SquareSum(n), set);
}

private static int SquareSum(int n) {
//计算各位数平方和
var sum = 0;
while(n > 0) {
sum += (n % 10) * (n % 10);
n = n / 10;
}
return sum;
}

private static bool IsHappy2(int n) {
//若一个数不是快乐数，其必定死在4手上，最终进入以下死循环
//4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
//4的各数位平方是16，将y进行2次各位数平方和计算
//若相等，则到达了4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
//这样的死循环或到达了1这样的快乐数结束值
//返回x == 1即可判定是不是快乐数
var x = n;
var y = n;
do {
x = SquareSum(x);
y = SquareSum(SquareSum(y));
} while(x != y);
return x == 1;
}

private static bool IsHappy3(int n) {
//参考IsHappy2
while(n != 1 && n != 4) {
var sum = 0;
while(n > 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
n = sum;
}
return n == 1;
}

}```

```True
False
False```