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, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example:
Input: 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
这个自己要随便写一下,找找规律,比如12就不是happy number
1^2+2^2=5
5^=25
2^2+5^2=29
2^2+9^2=85
8^2+5^2=89
8^2+9^2=64+81=145
1+16+25=42
16+4=20
4
16
1+36=37
9+49=58
25+64=89
当出现89时,意味着开始重复循环了。所以思路就是建立一个set,每次算好平方和以后检查一下是否在这个set中。如果在set中set.count()返回1,如果没有在set中,返回0.
class Solution {
public:
bool isHappy(int n) {
set<int> s;
int temp=0;
s.clear();
while(n!=1)
{
while(n>0)
{
temp+=(n%10)*(n%10);
n/=10;
}
if(s.count(temp))
{return false;}
else
{
s.insert(temp);
n=temp;
temp=0;
}
}
return true;
}
};