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
Solution: auxiliary function; loop calculates the sum of squares of each digit until the result is 1 (returns True) or repeats (returns false)
1 classSolution {2 Public:3 BOOLIshappy (intN) {4map<int,BOOL>m;5 intret=sum (n);6 while(ret!=1){7 if(m[ret]==true)return false;8m[ret]=true;9ret=sum (ret);Ten } One return true; A } - intSumintN) { - intret=0; the while(n) { -RET + = (n%Ten) * (n%Ten);//not supported (N%10) ^2 -N/=Ten; - } + returnret; - } +};
"Leetcode" 202-happy number