Fastest Java code so far with comments


  • 10
    P
    public class Solution {
        public boolean isHappy(int n) {
            /* Base cases */
            
            // A negative or zero value
            // is not a valid input
            // Return grumpily
            if (n < 1) {
                return false;
            }
            
            // You have entered
            // the chain of despair.
            // You will never be 
            // happy again
            if (n == 4
            ||  n == 16
            ||  n == 20
            ||  n == 37
            ||  n == 42
            ||  n == 58
            ||  n == 89
            ||  n == 145) {
                return false;
            }
            // Check Wikipedia for 
            // the explanation of despairing numbers
            // You don't need to remember all of them.
            // Just remembering one of them will do
            
            // You have achieved bliss
            if (n == 1) {
                return true;
            }
            
            // If none of the above
            // Keep searching
            return isHappy(getSumOfSquares(n));
        }
        
        private int getSumOfSquares(int num) {
            int sum = 0;
            while (num > 0) {
                int digit = num % 10;
                sum += digit * digit;
                num /= 10;
            }
            
            return sum;
        }
    }

Log in to reply
 

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