LeetCode202——快乐数
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/happy-number/description/
题目描述:
知识点:哈希表
思路:用HashSet存储出现过的数字,一旦出现重复说明该数不是快乐数
JAVA代码:
public class Solution {
public boolean isHappy(int n) {
HashSet<Integer> hashSet = new HashSet<>();
hashSet.add(n);
while(n > 1) {
ArrayList<Integer> arrayList = new ArrayList<>();
while(n > 0) {
arrayList.add(n % 10);
n /= 10;
}
n = 0;
for (int integer : arrayList) {
n += integer * integer;
}
if(hashSet.contains(n)) {
return false;
}else {
hashSet.add(n);
}
}
return true;
}
}
LeetCode解题报告: