原题链接:https://leetcode.com/problems/happy-number/description/
实现如下:
import java.util.HashSet;
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.isHappy(1));
System.out.println(s.isHappy(2));
System.out.println(s.isHappy(19));
}
/**
* 方法一:这道题目没看出啥太大的规律性,只简单的发现只要 n % 10 == 0 时,那么便是返回 true 的时候了;同时为了防止无限循环,必须用
* 一个数组来存储处理过的数值,若出现循环了则返回 false;
*
* @param n
* @return
*/
public boolean isHappy(int n) {
HashSet<Integer> set = new HashSet<>();
while (set.add(n)) {
if (n == 1) {
return true;
}
n = nextN(n);
}
return false;
}
private int nextN(int n) {
int res = 0;
while (n >= 10) {
int remainder = n % 10;
res += remainder * remainder;
n /= 10;
}
if (n > 0) {
res += n * n;
}
return res;
}
}