package com.zmz.algorithm.hashtable;
import java.util.HashSet;
/**
* @author 张明泽
* Create by 2022/5/30 18:25
* 快乐数
* LeetCode-202
*/
public class HappyNumber {
public static void main(String[] args) {
Boolean f = isHappy(2);
System.out.println(f);
}
public static Boolean isHappy(int n) {
HashSet<Integer> hashSet = new HashSet<>();
while (n != 1 && !hashSet.contains(n)) {
hashSet.add(n);
n = getNum(n);
}
if (hashSet.contains(n)) {
return false;
}
// 或者返回 n == 1
return true;
}
public static int getNum(int n) {
int sum = 0;
while (n > 0) {
sum = sum + (n % 10) * (n % 10);
n = n / 10;
}
return sum;
}
}
最后修改:2022 年 06 月 02 日 10 : 00 AM
© 允许规范转载