C中回文问题

时间:2012-03-05 10:31:53

标签: c algorithm palindrome

我在C中写了一些代码,试着找出一个数字是否是回文。规则是两个3位数字必须相乘,你必须找到最高的回文数。答案应该是906609,但我的代码只能达到580085.

代码:

#include <stdio.h>
#include <stdlib.h>

/* Intialise */
void CalcPalin();
int CheckPalin(int number);

/* Functions */
void CalcPalin()
{
    int result = 0;
    int palin = 0;
    int FNumber = 0;
    int FNumber2 = 0;

    int number = 99;
    int number2 = 100;

    while(number2 < 1000)
    {
        number += 1;

        /*times together - calc result*/
        result = number * number2;

        if(CheckPalin(result) == 1)
        {
            palin = result;
            FNumber = number;
            FNumber2 = number2;
        }

        if(number == 999)
        {
            number = 99;
            number2 += 1;
        }
    }
    printf(" Result = %d, by Multiplying [%d] and [%d]", palin, FNumber, FNumber2 );
}

int CheckPalin(int number)
{
    int checknum, checknum2 = 0;

    checknum = number;
    while(checknum)
    {
        checknum2 = checknum2 * 10 + checknum % 10;
        checknum /= 10;
    }

    if( number == checknum2)
        return 1;
    else
        return 0;
}

int main( void)
{
    CalcPalin();
    return EXIT_SUCCESS;
}

我很确定这是一个愚蠢的答案,我看起来很简单,但我似乎无法找到它。任何帮助都会很棒

2 个答案:

答案 0 :(得分:4)

您尚未测试当前结果是否高于一个旧结果。添加此项检查。

// test new result is higher than old palin before setting this as palin
if(CheckPalin(result) == 1 && palin < result) 

答案 1 :(得分:0)

您的算法打印:

 Result = 580085, by Multiplying [583] and [995]

似乎你应该找到增加第一个数字的方法。为了达到906609,在583和999之间有很多可能性。

编辑:事实上,您正在寻找993 * 913 = 906609.