My C# Solution using Hashset (No magic number 4!!)


  • 0
    J

    Many of the solution you guys provided has a magic number 4 in it. Is this some sort of mathematical property or just a hack to pass through the test cases?

    public class Solution {
        public bool IsHappy(int n) {
            HashSet<int> unhappy = new HashSet<int>();
            while (n != 1) {
                n = DigitSquareSum(n);
                if (unhappy.Contains(n)) return false;
                unhappy.Add(n);
            }        
            return true;
        }
        
        private int DigitSquareSum(int n) {
            int sum = 0; 
            if (n < 10) return n * n;
            else {
                while (n >= 10) { // when not a single digit
                    int r = n % 10; // r is the right-most digit
                    sum += r * r;   // r^2 and add it to the sum
                    n = n / 10;     // shift to the left
                } 
                // when a single digit
                sum += n * n;
            }
            return sum;
        }
    }

  • 0
    J

    I see some duplicate code logic already ㅜㅜ


Log in to reply
 

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