题解 | #奶牛快乐数# 快慢指针
奶牛快乐数
https://www.nowcoder.com/practice/d91cec70c7724a7dbcea02ed25bdeaee
知识点
快慢指针
思路
准备一个快指针一个慢指针,快指针每次走两次,慢指针每次走一次,如果快指针先到达1,说明是快乐的。如果存在环的话,那么走的足够多的时候快慢指针相等。
AC Code(C++)
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return bool布尔型
*/
bool isHappy(int n) {
// 快慢指针
int a = n, b = n;
while (true) {
a = get(get(a));
b = get(b);
if (a == 1) return true;
if (a == b) return false;
}
return true;
}
int get(int x) {
int res = 0;
while (x) {
int t = x % 10;
res += t * t;
x /= 10;
}
return res;
}
};
查看15道真题和解析
