本文共 762 字,大约阅读时间需要 2 分钟。
Well, no matter whether the number is happy or not, its sum-of-squared-digits sequance has a cycle. Well, do you still remember the algorithm for detecting cycles in linked lists? Yeah, use a fast and a slow pointer. That's also applicable to this problem.
The code is as follows (idea from ).
1 class Solution { 2 public: 3 bool isHappy(int n) { 4 int slow = n, fast = n; 5 do { 6 slow = squareDigits(slow); 7 fast = squareDigits(squareDigits(fast)); 8 } while (slow != fast); 9 return fast == 1;10 }11 private:12 int squareDigits(int n) {13 int sq = 0;14 while (n) {15 sq += (n % 10) * (n % 10);16 n /= 10;17 }18 return sq;19 }20 };
转载地址:http://alxca.baihongyu.com/