0202.快乐数
https://leetcode-cn.com/problems/happy-number
原题
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:
- 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
- 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
- 如果 可以变为 1,那么这个数就是快乐数。
如果n是快乐数就返回true;不是,则返回false。
示例 1:
输入:19输出:true解释:1^2 + 9^2 = 828^2 + 2^2 = 686^2 + 8^2 = 1001^2 + 0^2 + 0^2 = 1
示例 2:
输入:n = 2
输出:false
提示:
1 <= n <= 2^31 - 1
标签哈希表 数学 双指针
思路
代码
快慢指针
class Solution {
public:
bool isHappy(int n) {
// unordered_set<int> s;
int slow = n, fast = n;
while(slow != 1){
slow = func(slow);
fast = func(func(fast));
if(slow == fast) return slow == 1;
}
return true;
}
int func(int n){
int res = 0;
while(n){
int t = n%10;
res += t*t;
n /= 10;
}
return res;
}
};
哈希表
class Solution {
public:
bool isHappy(int n) {
unordered_set<int> s;
while(n != 1){
if(s.find(n) != s.end()) return false;
s.insert(n);
n = func(n);
}
return true;
}
int func(int n){
int res = 0;
while(n){
int t = n%10;
res += t*t;
n /= 10;
}
return res;
}
};
