Easy-to-understand short recursive Java solution using HashSet

  • 4

    Use HashSet to record numbers that have occured once so that when meet them the second time, we know it's NOT a Happy Number and it'll be a endless loop.

    HashSet<Integer> occured = new HashSet<>();
    public boolean isHappy(int n) {
        if (occured.contains(n)) return false;
        if (n == 1) return true;
        int res = 0;
        while (n != 0) {
            res += Math.pow(n % 10, 2);
            n /= 10;
        return isHappy(res);

  • 0

    One thing is to not use recursion and just run a while loop while n != 1, get the digits, add it to res, check if the set contains that value, if so, return false, else add it then set n = res and continue on.

Log in to reply

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