Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
题意:按照上例,拆分整数,得到平方和,如果最后结果为1,停止;如果结果为以前存在的数(陷入无限循环),也停止;
code:
package leetcode;
import java.util.*;
public class HappyNumber {
// 停止条件:要么sum=1;要么这些结果中包含了sum;
//对每个数字进行解析,利用可变数组进行存储得到的结果,判断是否为1还是有循环?
//while(true)的用法;
public static boolean isHappy(int n) {
/*
* int res = 0; Map<Integer, ArrayList<Integer>> map = new HashMap<>();
* // map.put(n, new ArrayList<>()); int sum = n; while (sum != 1) {
* List arr = new ArrayList(); map.put(sum, new ArrayList<Integer>());
* if (map.containsKey(sum)) return false; if (n <= 9) {
* map.get(sum).add(n); } else { while (n > 9) { res = n % 10;
* map.get(sum).add(res); n = n / 10; } } Iterator ite = new Iterator();
* for (int i = 0; i < map.get(sum).size(); i++) { int tmp = (Integer)
* map.get(sum).get(i); sum += tmp * tmp; }
*
* } return true;
*/
/* Map<Integer,ArrayList<Integer>> map = new HashMap<>(); */
List<Integer> arr = new ArrayList<>();
int sum = 0;
while (true) {
sum += (n % 10) * (n % 10); //只是对一个数字这样分析即可!!
n = n / 10;
if (n == 0) {
if (arr.contains(sum))
return false;
else if (sum == 1)
return true;
arr.add(sum);
n = sum;
sum = 0;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isHappy(7));
}
}