Happy Number
Happy Number
If n becomes 1 after repeatedly replacing it with the sum of squares of its digits, then the initial n is a happy number.
This problem tests your ability to detect cycles in results. We use the fast-slow pointer technique from cycle detection to see if n creates a loop after multiple iterations.
Floyd Cycle Detection
class Solution {
public:
bool isHappy(int n) {
int fast, slow;
fast = sum(n);
slow = n;
while(fast!=slow) {
slow = sum(slow); // slow moves one step
fast = sum(fast); // fast moves two steps
fast = sum(fast);
}
return slow == 1;
}
int sum(int n) {
int s=0;
int tmp;
while(n) {
tmp = n%10;
s += tmp*tmp;
n/=10;
}
return s;
}
};