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 here).
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 };
时间: 2024-10-17 06:28:14