代码改变世界

hdu 1282回文数猜想

2013-08-03 17:18  youxin  阅读(500)  评论(0编辑  收藏  举报

http://acm.hdu.edu.cn/showproblem.php?pid=1282

Problem Description
一个正整数,如果从左向右读(称之为正序数)和从右向左读(称之为倒序数)是一样的,这样的数就叫回文数。任取一个正整数,如果不是回文数,将该数与他的倒序数相加,若其和不是回文数,则重复上述步骤,一直到获得回文数为止。例如:68变成154(68+86),再变成605(154+451),最后变成1111(605+506),而1111是回文数。于是有数学家提出一个猜想:不论开始是什么正整数,在经过有限次正序数和倒序数相加的步骤后,都会得到一个回文数。至今为止还不知道这个猜想是对还是错。现在请你编程序验证之。
 
Input
每行一个正整数。
特别说明:输入的数据保证中间结果小于2^31。
 

 

Output
对应每个输入,输出两行,一行是变换的次数,一行是变换的过程。
 
Sample Input
27228
37649
 

 

Sample Output
3
27228--->109500--->115401--->219912
2
37649--->132322--->355553

 最开始的代码:(用尾递归)

#include<stdio.h>
 
static int nCount=0;
void func(int n)
{
    int n2=n;
    int tmp=0;
    while(n)
    {
        tmp*=10;
        tmp+=n%10;
        n/=10;
    }
    if(n2==tmp)
    {

            printf("%d\n",n2);
            printf("%d\n",nCount);
            return;
    }
    else
    {
        int newVal=n2+tmp;
        printf("%d--->",newVal);
        nCount++;
        func(newVal);
    }
}
int main()
{
    int n;
    bool flag=true;
    bool retVal;
    while(scanf("%d",&n)!=EOF)
    {
           nCount=0;
            func(n);
        
    }
}

输出:

27228
109500--->115401--->219912--->219912
3
37649
132322--->355553--->355553
2

 不满足要求,因为首先要输出变换的次数,这在程序中无法做到,因为nCount一开始不知道,我最开始项缓存printf()的输出,

类似php Ob_start() ;ob_ge_clean();但是C语言中没有类似方法。

最后参考网上一个代码:用数组保存结果:不要尾递归

int inverse(int num)
{
    int num2=num;
    int tmp=0;
    //使用循环把数字反转
    while(num!=0)
    {
        tmp*=10;
        tmp+=num%10;
        num/=10;
    }
    return tmp;
}
int main()
{
    int n,c[100];
    int count,i;
    while(scanf("%d",&n)!=EOF)
    {
        count=0;
        c[count]=n;;
        while(n!=inverse(n))
        {
            n+=inverse(n);
            c[++count]=n;
        }
        printf("%d\n",count);
         
        for(i=0;i<=count;i++)
        {
            if(i==0)
                printf("%d",c[i]);
            else
                printf("--->%d",c[i]);
        }
        printf("\n");
    }
}

这里有点巧妙,用count作为索引。

参考;http://blog.csdn.net/ysc504/article/category/1294840