Simple and Short solution in JAVA


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

  • 4
    A

    Your last two lines can be replaced with

    return n == 1;

Log in to reply
 

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