-1

I tried to do this question using strings and I am getting correct answers for the test cases on my compiler but spoj says Wrong answer.

I tried the hidden test case 0,0 and handled that too , still I am getting a wrong answer

#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int t=0,x=0,y=0,z=0,i=0;
    cin>>t;
    string s1,s2,s3;
    while(t--)
    {
        cin>>s1>>s2;
        reverse(s1.begin(),s1.end());
        reverse(s2.begin(),s2.end());
        x=stoi(s1);
        y=stoi(s2);
        z=x+y;
        s3=to_string(z);
        if(z!=0)
        {   
                for(i=0;s3[i]!='\0';i++)
            {
                if(s3[i]=='0')
                {
                    s3[i]='\0';
                    break;
                }       
            }
                reverse(s3.begin(),s3.end());
        }
        cout<<s3<<endl;
    }
}

I got correct answers on my compiler but when I submitted the same code on spoj , I got wrong answer. Could this be because the the website expected answer in int and I have printed Answer as String ?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
mujtaba1747
  • 33
  • 1
  • 6

1 Answers1

1

You should start with removing 0 from end of z integer before converting it into string

#include<bits/stdc++.h>
using namespace std;
int main()
{
    long long int t=0,x=0,y=0,z=0,i=0;
    cin>>t;
    string s1,s2,s3;
    while(t--)
    {
        cin>>s1>>s2;
        reverse(s1.begin(),s1.end());
        reverse(s2.begin(),s2.end());
        x=stoi(s1);
        y=stoi(s2);
        z=x+y;
        while(z%10==0)
            {
                z=z/10;

              }
        s3=to_string(z);

           reverse(s3.begin(),s3.end());

        cout<<s3<<endl;
    }
}
mss
  • 1,423
  • 2
  • 9
  • 18
  • Same for you: https://stackoverflow.com/questions/54160457/spoj-problem-addrev-adding-reversed-numbers-im-getting-a-wrong-answer-which#comment95151519_54160457 – πάντα ῥεῖ Jan 12 '19 at 15:10
  • Thanks a lot for your answer , it worked . But I am still not able to understand why my previous approach did not work ... – mujtaba1747 Jan 12 '19 at 15:15
  • @mujtaba1747 , I am happy I was able to help you :). – mss Jan 12 '19 at 15:16
  • your welcome. could you please explain me why my previous code gave error ... – mujtaba1747 Jan 12 '19 at 15:22
  • @mujtaba1747 this will help you , https://stackoverflow.com/questions/24453128/nul-char-in-strings-in-c/24453248 – mss Jan 12 '19 at 15:22
  • Thank you very much !!!!!!! .The link you shared explained it all.The reason why my previous code was not working is that in C++ , the string doesn't terminate at '\0' , it just treats it like null character. – mujtaba1747 Jan 12 '19 at 15:28