1 / 1
Jun 2012

I am getting WA for the following code of The Next Palindrome ... it is giving garbage values for long strings (like 200 or more characters).
bt it is giving AC if I output string p,character wise using a loop... Plz help me why it is giving garbage values. astonished

#include<iostream>
#include<string>
using namespace std;
void palindrome();
int main()
{
    int t=0;// test cases
    cin>>t;
    for(int i=0;i<t;i++)
    {
            palindrome();
    }
    return 0;
}
void palindrome()
{
     string n;// number
     cin>>n;
     int d=n.length();// no of digits
     string inlf=n.substr(0,(d+1)/2);
     string filf=n.substr(d/2,(d+1)/2);
     char copy[d/2+3];
     string comp=inlf;
     int k=comp.length();
     for(int i=0;i<k/2;i++)
     {
             char temp=comp[i];
             comp[i]=comp[k-1-i];
             comp[k-1-i]=temp;
     }
       for(int i=0;i<d/2;i++)
     {
             copy[d/2-1-i]=inlf[i];       
     }
     string p=inlf+copy;//palindrome
     if(d==1) p=inlf;
     if(d==2) p=inlf+inlf;
     if(d==3) { p=n; p[2]=n[0];}
     if(filf>=comp)
     {
                      int ch=n[((d-1)/2)]-48;
                      int i=0;
                      while(ch==9)
                      {
                           p[((d-1)/2)-i]='0';       
                           p[((d)/2)+i]='0';
                           ++i;
                           ch=n[((d-1)/2)-i]-48;
                           if(i==(d+1)/2) 
                           {
                                     break;
                           }
                      }
                       if(i==(d+1)/2&&n[0]=='9'&&n[1]=='9') 
                       {
                                 p[0]='1';
                                 for(int i=1;i<d;i++)
                                 {
                                         p[i]='0';
                                 }
                                 p=p+"1";
                       }
                       else
                       {
                            ++ch;
                            char change=ch+'0';
                            p[d/2+i]=change;
                            p[(d-1)/2-i]=change;
                            if (n=="9") p="11";
                        }
     }  
     cout<<p<<endl;
}

Thnx

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 17 11d

Want to read more? Browse other topics in C and C++ or view latest topics.