标签:fas next info 指针 com 快慢指针 color 技术 return
解法一:哈希表
class Solution { public: bool isHappy(int n) { 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 d = n % 10; totalSum += d * d; n = n / 10; } return totalSum; } };
解法二:快慢指针
class Solution { public: bool isHappy(int n) { int slow = n; int fast = getNext(n); while (slow != 1 && slow != fast) //快乐或者存在环跳出 { slow = getNext(slow); fast = getNext(getNext(fast)); } return slow == 1; } int getNext(int n) { int totalSum = 0; while (n > 0) { int d = n % 10; totalSum += d * d; n = n / 10; } return totalSum; } };
LeetCode 202. 快乐数 Happy Number
标签:fas next info 指针 com 快慢指针 color 技术 return
原文地址:https://www.cnblogs.com/ZSY-blog/p/12985455.html