Write an algorithm to determine if a number is "happy".
Write an algorithm to determine whether a number is a happy number.
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.
A happy number is defined as follows: Starting with an integer, followed by the sum of the squares of each digit of the integer instead of the number, and then repeating the process until the end is 1, or the loop is a dead loop that contains no 1. The final result of these processes is that 1 of these numbers are called happy numbers.
Example: is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
This topic really I did not think of a good idea, can think of a few points to say, the value of the square is only from 0-9 of the number of squares, so, a fixed array must be faster than the calculation of the square, directly can use the array subscript to take out the final result.
This problem is difficult in how to judge it is a cycle of death, and there is no 1. In addition to the loop enumeration I really did not think of any good method, I can only think, there must be several special cases are encountered must be a dead loop.
The answers on the web are like this, specifically
intDigitsquaresum (intN) {intsum =0, TMP; while(n) {tmp= n%Ten; Sum+ = tmp *tmp; N/=Ten; } returnsum;}BOOLIshappy (intN) {intslow, fast; Slow= Fast =N; Do{Slow=digitsquaresum (slow); Fast=digitsquaresum (FAST); Fast=digitsquaresum (FAST); } while(Slow! =fast); if(Slow = =1)return 1; Else return 0;}
This algorithm is the first time I have seen this, I have studied a good, and found that this is really a magic algorithm.
The name is called Floyd algorithm (Turtle and Rabbit Race algorithm)
First of all, to say, is to judge there is no ring, set two starting position of the same pointer, a run slow each run a cycle, a run of fast every run is equivalent to running two cycles, once they appear the same, then there must be a ring, and then we see the blame ring is not 1 can, One of the biggest advantages of this algorithm is that time complexity is low and space complexity is low, and you do not need to save each occurrence of the value and compare it to the previous value.
Explanation of the specific algorithm my side directly affixed to the address, reproduced from:
http://blog.csdn.net/wall_f/article/details/8780209
To tell the truth, I like this algorithm very much, really great!
leetcode202 (Floyd algorithm (Turtle-Rabbit race algorithm)