//方法一:
void isHappy(int n)
{
while (n != 1)
{
int n1 = 0;
int n2 = 0;
while (n)
{
n1 = n % 10;
n2 = n2 + n1 * n1;
n = n / 10;
}
n = n2;
if (n ==1)
{
printf("true\n");
break;
}
if (n < 10 && n != 1)
{
printf("false\n");
break;
}
}
}
int main()
{
int n = 0;
while (scanf_s("%d",&n))
{
isHappy(n);
}
return 0;
}
3.方法二:因为1 <= n <= 2^31 - 1,及为50位。后面一样的方法。
//方法二:
void isHappy(int n) {
int sum = 0;
int count = 0;
while (sum != 1 && count < 50) {
while (n != 0) {
sum = sum + (n % 10) * (n % 10);
n = n / 10;
}
if (sum == 1) printf("true\n");
n = sum;
sum = 0;
count++;
}
printf("false\n");
}
int main()
{
int n = 0;
while (scanf_s("%d",&n))
{
isHappy(n);
}
return 0;
}