Topic:
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
- 1^2 + 9^2 = 82
- 8^2 + 2^2 = 68
- 6^2 + 8^2 = 100
- 1^2 + 0^2 + 0^2 = 1
The more straightforward idea is to create a hash_table with a map with a value of 1 indicating that it is false. The case of N==1 is ruled out. But it takes 9ms and is inefficient.
classSolution { Public: BOOLIshappy (intN) {BOOLHappy =false; Unordered_map<int,int>MPs; intTmpnum =N; if(n = =1)return true; while(Tmpnum! =1) { intBuff =0; Mps[tmpnum]=1; while(Tmpnum%Ten!=0|| Tmpnum/Ten!=0) {Buff+ = (tmpnum%Ten) * (tmpnum%Ten); Tmpnum/=Ten; } tmpnum=Buff; if(Buff = =1) {Happy=true; Break; } Else if(Mps[buff] = =1) Break; } returnHappy; }};
Refer to the code of discussion's others, using only 4ms
classSolution { Public: BOOLIshappy (intN) {intsum =0; if(n = =1)return true; if(N <Ten&& n! =7)return false; while(n>=Ten) {sum+ = (n%Ten) * (n%Ten); N/=Ten; } Sum+ = nN; if(Sum = =1) { return true; } Else returnishappy (sum); }};
The use of recursive return judgment. For less than 10, it is not happy number except for 7
"Leetcode" 202. Happy number