int count(int n) {
int sum = 0;
while (n) {
sum += pow(n%10, 2);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
int t = 6;
while (t) {
n = count(n);
if (n == 1)
return true;
}
return false;
}
C++ 0 ms solution beats 98.32% cpp submissions

I'm curious too, empirical observation? One possiblity: The cycle length is 8 (
4, 16, 37, 58, 89, 145, 42, 20
). If something takes longer than this, it must be looping. Even the largest possible summed signed int1999999999
takes 2 steps to enter the cycle and in 1 steps it's already below 1000. Notice that it'st
which meanscount
will execute 7 times at most. I guess it assumes that the 7th transition will enter the loop at worst, otherwise it will stop onn == 1
. Note that the counting series decreases very fast.