弗洛伊德判圈法

如果一个有限状态机,迭代函数或者链表上存在环,那么在某个环上以不同速度跑路的两个指针必定会相遇。
一般一个步长1,一个步长2即可
对于本题判断相遇点是否为1即可。


#include<cstdio>
using namespace std;
class Solution {
   
public:
int fun(int n) {
   
	int sum = 0;
	while (n)
	{
   
		int temp = n % 10;
		sum += temp * temp;
		n /= 10;
	}
	return sum;
}
    bool isHappy(int n) {
   
	int slow = n;
	int fast = n;
	do {
   
		slow = fun(slow);
		fast = fun(fun(fast));
	} while (slow != fast);
	return slow == 1;
    }
};

顺嘴一提。leetcode这个main函数有点东西。。