这里的问题是:https://leetcode.com/problems/happy-number/函数返回false
我的解决办法:
static int count = 0;
public static void Main(string[] args)
{
Console.WriteLine(happyNumber(19));
Console.ReadLine();
}
public static bool happyNumber(int a)
{
double result = 0;
Stack<int> stapel = new Stack<int>();
//Split the integer into single digits and save them in a stack
while (a.ToString().Count() > 1)
{
stapel.Push(a % 10);
a = a/10;
}
if (a.ToString().Count() == 1)
{
stapel.Push(a);
}
// Add the square of the digits to get the result
foreach (var item in stapel)
{
result += Math.Pow((double)item, 2);
}
// Check if it's a happy number
if(result == 1.0)
{
return true;
}
// counter to stop if it is a endless loop
else if(count < 100)
{
count++;
happyNumber((int)result);
}
return false;
}
所以输入19是一个快乐号和4号if引导的从句是真实的跑。 您可以在if(result == 1.0)
处设置断点来检查它。那么为什么我的函数返回false呢?
检查是否(结果== 1) – Sachu
是的,它仍然是true,但我的函数将返回false, – johnas