Run Time 2ms using combination of recurision and itteration with explanation

  • 0

    The trick here is understanding when a cycle happens. 2000 and 2 produce the same results 4 so does 1000 and 100
    eventually all number being added will produce a digit that where the sum is a digit from 1-9. The reason for this is because the way we see number are in base 10.

    Next we focus on the prime numbers 1,2,3,5,7 from the range 1-9. Because all the non prime numbers in that range is just a bigger set variation from the prime range sets.


    Notice the pattern the answer revolves around 1 set as well as 2 set. 1 set or 2 set could be a sub-set of the other prime numbers!.

    So recursive condition when the sum of all squared "digits" is 1 return true else if the sum of all digits is 4(2^2) or negative (must be only positive numbers) return false.

    If conditions have not been met, add all the square of the digits or the number (iteration) and call the function again(recursion).

    Happy coding!

    class Solution {
        public boolean isHappy(int num) {
            if(num<0 || num==4){
                    return false;
            int results=0;
            while(num!=0) {
                int temp=num %10;
                Double tempResults=Math.pow(temp,2);
                return true;
            return isHappy(results);

Log in to reply

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