Home > Software engineering >  Finding next palindrome
Finding next palindrome

Time:02-20

I am trying to solve a problem related to palindrome which is:

"For each K, output the smallest palindrome larger than K." (Where K is an integer taken as user input)

I have used the recursive approach but it just throws an error stating SEGMENTATION FAULT....

My approach...

#include <iostream>
using namespace std;

int pal(int x){
    int rev=0;
    while(x!=0){
        int rem=0;
        rem=x;
        rev=rev*10   rem;
        x=x/10;
    } 
    if(rev==x)
        return x;
    else
        pal(x 1);
}

int main() {
    int T;
    cin>>T;
    while(T--){
        int N;
        cin>>N;
        
        cout<<pal(N 1)<<endl;
    }
    return 0;
}

Please guide me where am I doing wrong.

CodePudding user response:

Instead of writing

else {
pal(x 1);
}

write return pal(x 1);

Your current pal function does not return any value if the first x 1 is not a palindrome. Based on what @igorTandentik has written in the comments, this should fix the problem.


EDIT 1:

Your code has a serious flaw. You're making x zero in your while loop and then comparing it with reverse, which will never be true. Now you are calling pal with x 1 which is equivalent to pal(1). You repeat same mistake in recursive call. Hence you enter an infinite loop. Make a copy of x in your function then use that copy to reverse the x. use x to compare with reverse or forward it to next call.

  • Related