Skip to content

Latest commit

 

History

History
39 lines (32 loc) · 804 Bytes

Question_202.md

File metadata and controls

39 lines (32 loc) · 804 Bytes

LeetCode Records - Question 202 Happy Number

Attempt 1: Use HashSet to check repeated n

class Solution {
    HashSet<Integer> hashSet = new HashSet<>();

    public boolean isHappy(int n) {
        return isHappyRecursion(n);
    }

    boolean isHappyRecursion(int n) {
        if (hashSet.contains(n)) {
            return false;
        } else {
            hashSet.add(n);
        }

        int count = 0;
        while (n > 9) {
            int val = n % 10;
            count += val * val;
            n /= 10;
        }
        int val = n % 10;
        count += val * val;

        if (count == 1) {
            return true;
        }

        return isHappyRecursion(count);
    }
}
  • Runtime: 1 ms (Beats: 64.01%)
  • Memory: 40.68 MB (Beats: 48.75%)