My C# Solution using 66ms


  • 0
    O
    using System.Collections.Generic;
    public class Solution {
        public bool IsHappy(int n) {
            Dictionary<int,int> nums = new Dictionary<int,int>();
            while(!nums.ContainsKey(n))
            {
                int[] digits = digestNum(n);
                int sum = 0;
                for(int i = 0; i < digits.Length; i++)
                {
                    sum += digits[i] * digits[i];
                }
                if(sum == 1)
                {
                    return true;
                }
                else
                {
                    nums.Add(n,sum);
                    n = sum;
                }
            }
            return false;
            
        }
        
        private int[] digestNum(int n)
        {
            List<int> result = new List<int>();
            do
            {
                result.Add(n % 10);
                n = n / 10;
            }while (n > 0);
            return result.ToArray();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.