题目描述:
202. Happy Number
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: 19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
解题思路:
本题想法非常简单,即不停的迭代算下一次结果,看是不是满足数字之和为1。但是关键点在于如果该数字不是happy number,如何终止循环。此时考虑用一个map<int,bool>,,如果sum(所有数字的和)为1,则返回true。如果sum不为1,且为第一次出现,则将map[sum]的值置为true,意为该值已经出现过,如果之后再次出现相同的sum值,则说明此时该数陷入了一个循环,也即该数不是happy number,则返回false。
代码展示:
class Solution {
public:
bool isHappy(int n) {
if(n==0)
return false;
map<int,bool> res;
int sum =0;
while(1)
{
while(n>0)
{
sum+=pow(n%10,2);
n/=10;
}
if(sum==1) return true;
if(!res[sum]) //判断sum之前是否出现过,若未出现过则标记为已出现,同时将n置为sum,将sum置为0,开始下一次迭代
{
res[sum]=true;
n = sum;
sum=0;
}
else//如果出现过则说明此时陷入循环,不是happy number
{
return false;
}
}
return false;
}
};