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
According to the above rules, if we can satisfy the above rules, then it is a happy number.
Use a set to record that there has been a count, to avoid a dead loop
Public classSolution { Public BooleanIshappy (intN) {Set<Integer> set =NewHashSet (); returnishappynum (n, set); } Public BooleanIshappynum (intN, set Set) { if(Set.contains (n)) {return false; } set.add (n); intnum = 0; while(n! = 0) {num+ = (n%) * (n% 10); N/= 10; } if(num = = 1){ return true; } Else { returnishappynum (num, set); } }}
2, the use of O (1) space complexity. Very ingenious, if there will be a cycle of the situation, then X and Y will meet, will certainly jump out of the loop.
Public classSolution { Public BooleanIshappy (intN) {intx =N; inty =N; while(x>1) {x=cal (x); if(x==1)return true ; Y=Cal (Cal (y)); if(y==1)return true ; if(x==y)return false; } return true ; } Public intCalintN) { intx =N; ints = 0; while(x>0) {s= S+ (x%10) * (x%10); X= X/10; } returns; }}
Leetcode 202. Happy number Determines whether a count is "Happy numbers"----------Java