Use recursion and set


  • 0
    I

    This is my solution using recursion and set to determine the happy number

    public boolean isHappy(int n) {
        
        Set<Integer> set = new HashSet<Integer>();
        
        return check(n, set);
    }
    
    
    private boolean check(int n, Set<Integer> set){
        
        if(n<10){
            if(n == 1){
               return true;
            }else if(set.contains(n)){
                return false;
            }else{
                set.add(n);
            }
            n = n*n;
        }
        
        int sum = 0;
        while(n>=1){
            
            sum +=  Math.pow(n%10,2);
            n = n/10;
        }
        
        return check(sum, set);
    }

Log in to reply
 

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