題目: LeetCode - 202. Happy Number

題目說明

將題目給的數字拆開並求出拆開的數字的平方和,若結果為 1 則為 Happy Number。

解題思路

使用 Floyd Cycle Detection Algorithm 即可,詳細介紹可參考:Wiki

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int next(int n)
{
int next = 0;
while( n > 0)
{
next += (n % 10) * ( n % 10);
n /= 10;
}
return next;
}

bool isHappy(int n) {
int tortoise = n;
int hare = n;
do
{
tortoise = next(tortoise);
hare = next(next(hare));
}while(tortoise != hare);
return (hare == 1);
}
};