202. Happy Number

time: O(logn)

space: O(logn)

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> set = new HashSet<>();
        while (set.add(n)) {
            int sum = 0;
            while (n != 0) {
                int remain = n % 10;
                sum += remain*remain;
                n = n/10;
            }
            n = sum;
            if (n == 1) {
                return true;
            }
        }
        return false;
    }
}

/*
2

4

16

1 + 36 = 37

9 + 49 = 58

25 64

89

64 81 = 145

1 + 16 + 25 = 42

16 4 = 20

4 -- repeat!
*/

Last updated