class Solution {
public boolean isHappy(int n) {
if(n==1||n==-1)
return true;
HashSet<Integer>h=new HashSet<Integer>();
int m=0;
while(true)
{
while(n!=0)
{
m=m+(n%10)*(n%10);
n/=10;
}
if(m==1)
return true;
else if(!h.add(m))
return false;
n=m;
m=0;
}
}
}
笔记
1.hashset与hashmap区别:https://www.cnblogs.com/codercui/p/6841730.html
主要区别是hashmap存的是键值对而hashset存的是元素,hashmap不允许关键值key重复,hashset不允许元素重复。
2.定义hashset: HashSet<Integer> h = new HashSet<>();
3.add方法返回布尔量. boolean b1 = hashset1.add("111");若set中没有111,则返回true,否则返回false