#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」のある行) がある場合とない場合の 2 つの異なる回答が返されます。
出力は次のとおりです。
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
2 番目の出力は目的の出力です。この違いの原因と、最初のものの不正確さを指摘できますか?