lundi 25 mai 2015

Functions returns false even when the if statement is true

Here is the problem: http://ift.tt/1ySeXZF

My solution:

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;
}

So the input 19 is a happy number and the if clauses is true in the 4th run. You can set a Breakpoint at if(result == 1.0) to check it. So why my function returns false instead?

Aucun commentaire:

Enregistrer un commentaire