Happy Numbers


Sample Code. (Excludes input checking)

        protected void Button1_Click(object sender, EventArgs e)
        {
            int value = Convert.ToInt32(valueToTest.Text);

            bool isHappy = checkIfHappy(value);

            if (isHappy)
            {
                happyResult.Text = "Happy";
            }
            else
            {
                happyResult.Text = "Unhappy";
            }

        }

        private bool checkIfHappy(int value)
        {
            List<int> previousValues = new List<int>();
            bool? happy = null; // Nullable bool.

            while (happy == null)
            {
                previousValues.Add(value);
                int nextValue = calculateNextStep(value);

                if (previousValues.Contains(nextValue))
                {
                    happy = false;
                }

                if (nextValue == 1)
                {
                    happy = true;
                }

                value = nextValue;
            }

            return (bool)happy;
        }

        private int calculateNextStep(int value)
        {
            int total;

            // Basecase
            if (value < 10)
            {
                total = value * value;
            }

            else
            {
                int lastDigit = (value % 10)*(value % 10);
                total = calculateNextStep(value / 10) + lastDigit;
            }
            return total;
        }