Easy-understanding and very efficient Java solution


  • 1
    Y
    public boolean isHappy(int n) {
        HashSet<Integer> hash = new HashSet<Integer>();
        if(n <= 0) return false;
        while(n < Integer.MAX_VALUE){
            int i = 0;
            int j = 10;
            if(n == 1) return true;
            if(hash.contains(n)) return false;
            else hash.add(n);
            while(n != 0){
                i += (n % j) * (n % j);
                n = (n - n % j) / 10;
            }
            n = i;
        }
        return false;
    }

Log in to reply
 

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