UVa 10591 Happy Number

UVa 10591 Happy Number

迭代得到Si的值,同时用set记录已经计算过的Si。如果出现1,成功;如果出现了已经出现过一次的值,失败(因为之后也不会再出现1)。
以下是我的代码:

#include < set >
#include
< cstdio >
using   namespace  std;

int  f( int  x)
{
    
int  re( 0 );
    
while (x > 0 )
    {
        
int  t(x % 10 );
        re
+= t * t;
        x
/= 10 ;
    }
    
return  re;
}

int  main()
{
    #ifndef ONLINE_JUDGE
    freopen(
" data.in " , " r " ,stdin);
    freopen(
" data.out " , " w " ,stdout);
    
#endif

    
int  T;
    scanf(
" %d " , & T);
    
for ( int  case_num = 1 ;case_num <= T;case_num ++ )
    {
        
int  n;
        scanf(
" %d " , & n);
        printf(
" Case #%d: %d is  " ,case_num,n);

        
set < int >  r;
        
bool  success( false );
        
while ( true )
        {
            
if (n == 1 )
            {
                success
= true ;
                
break ;
            }
            
else   if (r.count(n) == 1 )
            {
                success
= false ;
                
break ;
            }
            r.insert(n);
            n
= f(n);
        }

        
if (success)
            printf(
" a Happy number.\n " );
        
else
            printf(
" an Unhappy number.\n " );
    }
}

你可能感兴趣的:(UVa 10591 Happy Number)