# [202\. Happy Number](https://leetcode.com/problems/happy-number/) Happy Number 的定義 [Happy number - Wikipedia](https://en.wikipedia.org/wiki/Happy_number) :::spoiler Solution - HashSet ```cpp= class Solution { public: bool isHappy(int n) { unordered_set<int> seen; while (n != 1 && !seen.count(n)) { seen.insert(n); n = getNext(n); } return n == 1; } int getNext(int n) { int totalSum = 0; while (n > 0) { int digit = n % 10; n = n / 10; totalSum += digit * digit; } return totalSum; } }; ``` - 時間複雜度:$O(\log n)$ - 空間複雜度:$O(\log n)$ ::: :::spoiler Solution - Floyd's Cycle-Finding Algorithm ```cpp= class Solution { public: bool isHappy(int n) { int slow = n; int fast = getNext(n); while (fast != 1 && slow != fast) { slow = getNext(slow); fast = getNext(getNext(fast)); } return fast == 1; } int getNext(int n) { int totalSum = 0; while (n > 0) { int d = n % 10; n = n / 10; totalSum += d * d; } return totalSum; } }; ``` - 時間複雜度:$O(\log n)$ - 空間複雜度:$O(1)$ :::