Why my solution works?


  • 0
    I

    My intuition says that loop for every unhappy number will contain one which is (1 < x < 10). So, I've tried the following solution which passed all test cases. But I don't know how to prove that mathematically. Any suggestions?

    public bool IsHappy(int n) {
        int summ = 0;
        while ( n > 0) {
            int tmp = n % 10;
            summ = summ + (tmp*tmp);
            n = (n - tmp)/10;
        }
        if (summ >= 10)
        {
            return IsHappy(summ);
        }
        
        return (summ == 1);
    }

Log in to reply
 

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