0
#include <iostream>
#include <vector>
#define MAXX 1000
using namespace std;

int number[MAXX], digits=0;
int adjust(int i)
{
    if(number[i]<9)
    {
        cout<<"i = "<<i<<" "; //PROBLEM
        (number[i])++;
        return i;
    }

    number[i]=0;
    adjust(i-1);
}

void makePalindrome(int head,int tail)
{
    int revert;
    if(head>tail)
        return;

    if(number[head]==number[tail])
    {
        makePalindrome(head+1,tail-1);
    }
    if(number[tail]<number[head])
    {
        number[tail]=number[head];
        makePalindrome(head+1,tail-1);
    }
    if (number[tail]>number[head])
    {
        number[tail]=number[head];
        revert=adjust(tail-1);
        if(revert<=head)
        {
            makePalindrome(revert,digits-revert-1);
        }
        else
        {
            makePalindrome(head+1,tail-1);
        }
    }
}

int main(int argc, char const *argv[])
{
    long long int num,num_copy;
    int head,tail;
    int number_reverse[MAXX];
    cout<<"Enter the number whose next greater palindrome you want to find"    <<endl;
    cin>>num;
    num_copy=num;

    while(num_copy>0)
    {
        number_reverse[digits]=num_copy%10;
        digits++;
        num_copy=num_copy/10;
    }

    //cout<<"Digits = "<<digits<<"\n";
    for (int i = digits-1; i >=0; --i)
    {
        number[digits-i-1]=number_reverse[i];
        //cout<<number[digits-i-1]<<" ";
    }
    head=0; tail=digits-1;
    makePalindrome(head,tail);
    cout<<"Answer : ";
    for (int i = 0; i < digits; ++i)
    {
        cout<<number[i];
    }
    cout<<"\n";
    return 0;
}

当我使用输入运行时:94187978322,它给出了两个不同的答案,有和没有“cout”行(带有注释“PROBLEM”的行)。

这是输出:

ishivendra:code shivendraagrawal$ g++ next_palindrome.cpp 
ishivendra:code shivendraagrawal$ ./a.out
Enter the number whose next greater palindrome you want to find
94187978322
Answer : 94188078149
ishivendra:code shivendraagrawal$ g++ next_palindrome.cpp 
ishivendra:code shivendraagrawal$ ./a.out
Enter the number whose next greater palindrome you want to find
94187978322
i = 7 i = 6 i = 4 Answer : 94188088149

第二个输出是期望的输出。您能否指出第一个差异和不正确的原因?

4

1 回答 1

0

我想通了一半,这是一个逻辑错误。我应该写return adjust(i-1)的。我仍然不知道这种特殊性的原因(没有编译或运行时错误),但至少我的代码现在可以按需要运行。

于 2013-10-30T17:27:14.743 回答