Happy Number 题目: https://leetcode.com/problems/happy-number/
解题思路:
1.新建一个set,存储计算过程中获得值
如果元素!=1 && 不再set中 加入set集合,计算累加和获得新的值, 最终如果是快乐数最终结果为1,如果不是快乐数,最终结果不为1.
public static void main(String[] args) {
int n=19;
boolean happy = isHappy(n);
System.out.println(happy);
}
public static boolean isHappy(int n) {
Set<Integer> set=new HashSet<>();
while(n!=1 && !set.contains(n)){
set.add(n);
n=getSum(n);
System.out.println(n);
}
return n==1;
}
/**
* 获取各个元素的累加和
* @param n
* @return
*/
public static int getSum(int n){
int result=0;
while(n!=0){
int ge=n%10;
result+=Math.pow(ge,2);
n/=10;
}
return result;
}