202. 快乐数 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/happy-number/要判断sum有没有出现过,最好用hash.
class Solution {
public boolean isHappy(int n) {
char[] chars = null;
int[] nums = null;
int sum;
Set<Integer> set = new HashSet<>();
while (true) {
chars = Integer.toString(n).toCharArray();
nums = new int[chars.length];
for(int i=0;i<chars.length;i++){
nums[i]=chars[i]-48;
}
sum = 0;
for (int i : nums) {
sum += i * i;
}
if(set.contains(sum))
return false;
if (sum == 1)
return true;
else {
set.add(sum);
n = sum;
}
}
}
}