My solution in recursive way


  • 0
    public boolean isHappy(int n) {
            HashSet<Integer> set = new HashSet<Integer>();
            return isHappyNumber(n, set);
        }
        public boolean isHappyNumber(int num, HashSet<Integer> set){
            if(set.contains(num)) return false;
            set.add(num);
            int newNum = 0;
            while(num != 0){
                newNum += (num % 10) * (num % 10);
                num /= 10;
            }
            if(newNum == 1) return true;
            return isHappyNumber(newNum, set);
        }
    

Log in to reply
 

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