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
Leetcode new topic, the main idea: given a number, each of its squares and add a new number, in this cycle, the final number if it is 1, then the given number is happy numbers, otherwise it will be endless loop.
Problem-solving ideas: The first direct simulation, the cycle 100 times is not 1 directly cut off return false, but also can AC, but after all, there may be situations covered, instead of hastset storage in the middle number on the line, if the resulting new results in the middle of the collection, Then it is bound to fall into the loop and get not 1.
Talk is cheap>>
Public BooleanIshappy (intN) {Set<Integer> res =NewHashset<>(); intsum =N; while(Sum! = 1) {n=sum; Sum= 0; while(n! = 0) {sum+ = (n%) * (n% 10); N/= 10; } if(Res.contains (sum)) {return false; } res.add (sum); } return true; }
Happy Number--leetcode