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
Ideas:
This topic is very interesting, certainly can not really through the infinite cycle to judge. I looked at the numbers that were not happy, and the numbers that had already appeared before the operation, that is, circled in a set of numbers. Therefore, record the number of occurrences and decide whether to repeat.
If the repetition is not happy, get 1 happy.
BOOLIshappy (intN) {unordered_set<int>record; while(1) { intsum =0; while(N >0) {sum+ = (n%Ten) * (n%Ten); N/=Ten; } if(Sum = =1) return true; if(Record.find (sum) = = Record.end ())//The current number has not appeared.{record.insert (sum); N=sum; } Else return false; } }
Also useful O (1) space, like a chain list to find a circle, with the idea of a fast and slow pointer.
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; }}
Also useful in mathematics, all the numbers that are not happy will get 4. Why
BOOLIshappy (intN) {if(N <=0)return false; intMagic =4; while(1) { if(n = =1)return true; if(n = = Magic)return false; intt =0; while(n) {T+ = (n%Ten) * (n%Ten); N/=Ten; } N=T; }}
"Leetcode" Happy number (Easy)