Java hashset solution, any suggestions?


  • 2
    X

    Use hash set to find if there is endless loop.

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

  • 5
    B

    Let's make the code shorter:

    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        while(n != 1 && !set.contains(n)){
            set.add(n);
            int next = 0;
            do{
                next += (n % 10) * (n % 10);
            }while((n /= 10) > 0);
            n = next;
        }
        return n == 1;
    }

  • 0
    M

    good solution


Log in to reply
 

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