Title:
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: is a happy number
- 1^2 + 9^2 = 82
- 8^2 + 2^2 = 68
- 6^2 + 8^2 = 100
- 1^2 + 0^2 + 0^2 = 1
Tips:
The key to the problem is to determine if the calculation of happy number is in the loop. One is the sum of squares calculated for each step and inserted into the hash set, if the number already exists, indicating that it has entered the loop state, then the number is not happy.
Another method is to save the sum of squares into an array (vector). Then each traversal to find the square and whether it has ever occurred.
Although the hash set is O (1), the vector traversal is O (n), but because the number is not many, the method of traversing is also very fast.
Pure Mathematical Method:
There is a mathematical proof of the cyclic sequence of happy number, and we can judge whether there is a loop by judging the sum of squares and whether "4" is present. See this article for specific proof.
Code:
Here's how to use vector traversal:
classSolution { Public: BOOLIshappy (intN) {vector<int>Nums; intresult; while(true) { if(n = =1)return true; Nums.push_back (n); Result=0; while(n! =0) {result+ = (n%Ten) * (n%Ten); N= N/Ten; } for(inti =0; I < nums.size (); ++i) {if(Nums[i] = = result)return false; } N=result; } }};
"Leetcode" 202. Happy number