1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { private static final Set<Integer> notHappyNumSet = new HashSet<>(Arrays.asList(2, 4, 16, 37, 58, 89, 145, 42, 20));
public boolean isHappy(int n) { while (n != 1 && !notHappyNumSet.contains(n)) { n = squareSum(n); }
return n == 1; }
private int squareSum(int n) { int sum = 0; while (n > 0) { int x = n % 10; sum += x * x; n /= 10; } return sum; } }
|