bool isHappy(int n) {
while (n!=1 && n!=4) {
int next_n = 0;
while (n>0) {
int k = n % 10;
next_n += k*k;
n /= 10;
}
n = next_n;
}
if (n==1) return true;
else return false;
}
2ms C code with O(1) space

4 will lead to cycle(infinite loop), and 4 is an unhappy number.
In fact, I guess we can enumerate more other unhappy number to speed up the process of eliminate.Pls ref :
http://en.wikipedia.org/wiki/Happy_number#Sequence_behavior