Given a number, in the form of an array a[] containing digits from 1 to 9(inclusive). The task is to find the next smallest palindrome larger than this number. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Wednesday, 22 July 2020

Given a number, in the form of an array a[] containing digits from 1 to 9(inclusive). The task is to find the next smallest palindrome larger than this number.


Given a number, in the form of an array a[] containing digits from 1 to 9(inclusive). The task is to find the next smallest palindrome larger than this number.

Next Smallest Palindrome

Given a number, in the form of an array a[] containing digits from 1 to 9(inclusive). The task is to find the next smallest palindrome larger than this number.


In each separate line print the digits of palindrome with spaces in between.
#include <iostream>
using namespace std;

int main() {
    //code
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int a[n];
        for(int i=0;i<n;++i)
        {
            cin>>a[i];
        }
        //f is flag variable for increasing the middle value
//flag is 1 that mean increase the middle value by one
//when overfflow the add to left make mirror to right
        int i,j,f=1;
        if(n%2==0)
        {
            i=n/2-1;//if n is even
            j=n/2;//there is two middle number
        }else{
            i=j=n/2;
        }
       
         while(i>=0&&j<n)
           {
 /left and right are same skip
 //when left is smaller than right then need to make it bigger than given number
//when right is smaller than left then already bigger so no need to add
                if(a[i]<a[j])
                {
                f=1;
                break;
                }else if(a[i]>a[j])
                {
                    f=0;
                    break;
                }
                ++j,--i;
           }
       
        i=0,j=n-1;
        //just make mirror of left to right
        while(i<j)
        {
            if(a[i]!=a[j])
            a[j]=a[i];
            ++i,--j;
        }
       
        if(f)
        if(n%2==1)
        {
//if middle is 9 and odd length then on adding become 10 ,only 0 is put
// 1 is added to left and make mirror also right
            if(a[n/2]==9)
            {
                a[n/2-1]+=1;
                a[n/2]=0;
                a[n/2+1]=a[n/2-1];
            }
           else
             {
                a[n/2]+=1;
             }
        }
        else
        {
            a[n/2]+=1;
            a[n/2-1]+=1;
         }
       
        for(int i=0;i<n;++i)
        {
            cout<<a[i]<<" ";
        }
        cout<<endl;
    }
    return 0;
}