[LeetCode]202. Happy Number

题目描述:

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

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

思路:

思路:一个快乐数指的是各位数字的平方的和加起来,不断计算,最终收敛为1。对于某一个正整数,如果对其各个位上的数字分别平方,
然后再加起来得到一个新的数字,再进行同样的操作,如果最终结果变成了1,则说明是快乐数,如果一直循环但不是1的话,就不是快乐数,否则会陷入死循环。
给出一个整数,判断是否为快乐数。
如果不是快乐数。如11,计算过程如下:
1^2 + 1^2 = 2
2^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4
会陷入4的死循环
可以用set来记录所有出现过的数字,然后每出现一个新数字,在set中查找看是否存在,若不存在则加入表中,
若存在则跳出循环,并且判断此数是否为1,若为1返回true,不为1返回false
set中不存在重复的对象
首先判断是否小于0.小于0则返回false
当n不等于1时,将n存储到set内,对n计算各位数字的平方和,记为新的n。判断n是否在set中出现过,如果出现过则表示陷入循环了。返回false
否则将n存入set中去,继续判断新的n

第二种方法是:
非快乐数必然在循环中出现4,只需判断是否在循环中n出现过4,出现则false

 1 public class Solution202 {
 2     public boolean isHappy(int n) {
 3         HashSet<Integer> set  = new HashSet<>(32);
 4         if(n <= 0) return false;
 5         while(n!=1){
 6             int tmp = 0;
 7             set.add(n);
 8             while(n>0){
 9                 tmp+=(n%10)*(n%10);
10                 n/=10;
11             }
12             n = tmp;
13             if(set.contains(n)) break;
14             else {
15                 set.add(n);
16             }
17         }
18         return n == 1;
19         /*第二种方法:判断循环中是否出现4即可
20           while (n != 1 && n != 4) {
21             int t = 0;
22             while (n>0) {
23                 t += (n % 10) * (n % 10);
24                 n /= 10;
25             }
26             n = t;
27         }
28         return n == 1;
29         */
30     }
31     public static void main(String[] args) {
32         // TODO Auto-generated method stub
33         Solution202 solution202 = new Solution202();
34         int n = 19;
35         System.out.println(solution202.isHappy(n));
36     }
37 
38 }
原文地址:https://www.cnblogs.com/zlz099/p/8249944.html