LeetCode 202. 快乐数 Happy Number

大鹏一日同风起,扶摇直上九万里。这篇文章主要讲述LeetCode 202. 快乐数 Happy Number相关的知识,希望能为你提供帮助。

LeetCode 202. 快乐数 Happy Number

文章图片

 
  解法一:哈希表
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; } };

【LeetCode 202. 快乐数 Happy Number】 
解法二:快慢指针
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; } };

 

    推荐阅读