题目来源:链接: [https://leetcode-cn.com/problems/perfect-squares/]
202. 快乐数
1.问题描述
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例1:
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
2.我的解决方案
easy 类型题目。
这题的关键点就是:无限循环但始终变不到 1的数 如何退出循环。
AC代码:
class Solution {
public:
bool isHappy(int n) {
map<int, bool> res;
int sum = 0;
while(1)
{
int sum = 0;
while(n)
{
int tmp = n%10;
sum += tmp*tmp;
n /= 10;
}
if(1 == sum)
{
return true;
}
else if(res.find(sum) == res.end()) //继续上述操作
{
res[sum] = true;
n = sum;
}
else //判断条件 若 两者不相等,说明出现了 无限循环 且 结果不等于1的数
{
return false;
}
}
}
};
3.大神们的解决方案
方法1:(递归)(速度 8ms)
class Solution {
public:
bool isHappy(int n) {
if(n<=4){
if(n==1)return true;
else return false;
}
int sum=0;
while(n){
sum+=(n%10)*(n%10);
n=n/10;
}
return isHappy(sum);
}
};
方法2:(速度第一 4ms)
这题有点 以空间 换取 时间的意思。
class Solution {
public:
bool isHappy(int n) {
assert(n > 0);
if (n <= 0) return false;
if (n < 10) return 1 == n || 7 == n;
int result_tmp = n;
while (true) {
result_tmp = loop(result_tmp);
if (result_tmp < 10) return 1 == result_tmp || 7 == result_tmp;
}
}
private:
int loop(int n) {
static const int arr[10] = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 };
int tmp = n;
int result = 0;
while (tmp > 0) {
int remainder = tmp % 10;
result += arr[remainder];
tmp /= 10;
}
return result;
}
};
4.我的收获
快乐就完事儿了。。。
2019/4/27 胡云层 于南京 67