Solution in Java using HashSet


  • 0
    G
    public boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet();
        set.add(n);
        
        return helper(n, set);
    }
    
    public boolean helper(int n, HashSet<Integer> set){
        if(n == 1)
            return true;
            
        int num = 0;
        while(n > 0){
            num += Math.pow(n % 10, 2);
            n /= 10;
        }
        
        if(set.add(num))
            return helper(num, set);
        
        return false;
    }

  • 0
    M

    Nice and clear, but it does not consume constant space on the stack; i.e. helper is not tail recursive. i believe that an iterative solution in this particular case is also more elegant.


  • 0
    G

    Thank you for your reply. :) You are right, it is not a constant space solution. I did some research on tail recursive and realised that Java might not support tail recursive optimization though.


Log in to reply
 

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