LeetCode/com/zerroi/leetcode/Three20/IsHappy.java

41 lines
898 B
Java

package com.zerroi.leetcode.Three20;
import java.util.HashMap;
import java.util.Map;
public class IsHappy {
public static void main(String[] args) {
SolutionFirst solutionFirst = new SolutionFirst();
boolean res = solutionFirst.isHappy(2);
System.out.println("res = " + res);
}
}
class SolutionFirst {
public boolean isHappy(int n) {
return isHappyHelper(n, new HashMap<>());
}
private boolean isHappyHelper(int n, Map<Integer, Integer> map) {
if (n == 1) return true;
int key = getNum(n);
if (map.containsKey(key)) {
return false;
}
map.put(key, 1);
return isHappyHelper(key, map);
}
private int getNum(int n) {
int sum = 0;
while (n > 0) {
int a = n % 10;
n /= 10;
sum += a * a;
}
return sum;
}
}