一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
例如:19就是快乐数
解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
public bool IsHappy(int n) {
HashSet<int> hashInt = new HashSet<int>();
return checkHappy(n,hashInt);
}
public static bool checkHappy(int n, HashSet<int> hashInt)
{
int sum = 0;
while (n != 0)
{
sum = sum + (n % 10) * (n % 10);
n = n / 10;
}
if (sum == 1) return true;
else
{
if (hashInt.Contains(sum)) return false;
else
{
hashInt.Add(sum);
return checkHappy(sum, hashInt);
}
}
}
如果研究这个快乐数的规律就可以发现,所有不快乐数的数位平方和计算,最後都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中。所以HashSet<int> hashInt = new HashSet<int> { 4, 16, 37, 58, 89, 145, 42, 20 };这样可以减少代码执行的时间!