# 202. Happy Number

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MkXQI0I1WRiTJYZG-gL%2F-MkXS7xyicrfa8yy4GRF%2Fimage.png?alt=media\&token=c2cbef14-5801-4f8e-b78a-459053e298fc)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MkXQI0I1WRiTJYZG-gL%2F-MkXSAkZv6NqXkEEQahn%2Fimage.png?alt=media\&token=f9686011-569c-4cd0-aeb5-cce17bc96bce)

time: O(logn)

space: O(logn)

```java
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!
*/
```
