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 and replace the number by the Sum of the squares of its digits, and repeat the process until the number equals 1 (where it would stay), or it loops Endl essly in a cycle which does not include 1. Those numbers for which this process ends in 1 is happy numbers.
Example:19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
Title meaning: For any positive integer, the sum of squares of each digit is added and then a new positive integer is obtained, and if the final convergence of this process is 1, then the number is happy numbers, otherwise the program may start to loop from a certain number.
1 Public BooleanIshappy (intN) {2 if(N < 1)return false;3Hashset<integer> set =NewHashset<> (32);//used to hold the results of intermediate occurrences4Set.add (1);5 inttmp;6 intnewn;7 //the value of n cannot recur, otherwise it will die loop8 while(!set.contains (n)) {9 Set.add (n);Tennewn = 0; One while(N > 0) { ATMP = n 10; -N/= 10; -newn + = tmp *tmp; the } -n =newn; - } - returnn = = 1; +}
202. Happy number