题目:求一个数每个数位上数字的平方和,为最后是否能转换化1。
分析:简单题、数论。求循环节。因为9^9*9 < 1000所以数据的转化集合是(1,1000),直接暴力模拟即可。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int used[ 1000 ];
int bitsv( int v )
{
int sum = 0;
while ( v ) {
sum += (v%10)*(v%10);
v /= 10;
}
return sum;
}
int happy( int v )
{
memset( used, 0, sizeof(used) );
v = bitsv(v);
while ( v != 1 && !used[v] ) {
used[v] = 1;
v = bitsv(v);
}
if ( v == 1 )
return 1;
return 0;
}
int main()
{
int N,T;
while ( scanf("%d",&T) != EOF )
for ( int t = 1 ; t <= T ; ++ t ){
scanf("%d",&N);
if ( happy(N) )
printf("Case #%d: %d is a Happy number.\n",t,N);
else
printf("Case #%d: %d is an Unhappy number.\n",t,N);
}
return 0;
}