您的位置:首页 > 移动开发

【LeetCode】202. Happy Number

2016-04-27 16:23 417 查看
题目:

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

理解:

判断一个数是否”happy“。

“happy"的定义是:计算这个数各个位置上的数的平方和,再计算这个平方和各个位置上的数的平方和,循环得到平方和为1,则这个数”happy“;否则,若中间某个平方和的值之前已经出现过,则说明循环永远得不到平方和为1,则这个数不是happy number。

分析:

1.计算给定数(或当前平方和)各个位置上的数的平方和,若该平方和为1,返回true;否则转2;

2.判断这个平方和是否已经出现过,若已经出现过,返回false;否则转1。

由于要记录下已经出现的平方和的值,并且在下次要迅速检索到当前平方和是否已经出现过,因此如果用C++,使用map存储再合适不过了。

代码:

class Solution {
public:
bool isHappy(int n) {
unordered_map<int, bool> m;
int sum=GetSum(n);
while(sum!=1)
{
if(m[sum]==true)
return false;
m[sum]=true;
sum=GetSum(sum);
}
return true;
}

int GetSum(int num)
{
int sum=0;
while(num!=0)
{
int digit=num%10;
sum+=(digit*digit);
num/=10;
}
return sum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: