1 / 5
Jun 2020

Hello, I attempted the ADDREV question, HERE1. My code gives matches the example output for the example input, but gives a wrong answer when submitted. Please can you look into it and help me find whats wrong.
CODE:

#include<iostream>
#include<math.h>
using namespace std;

//funtion for reversing the number

int rev_num(int n){
    if(n==0) return 0;
    int result=0,digits=0,temp;
    temp=n;

    // getting number of digits for n

    while(temp!=0){
        temp=temp/10;
        digits++;
    }

    //reversing the number

    for(int i=0;i<digits;i++){
        int rem=0;
        rem=n%10;
        n=n/10;
        result=result+rem*pow(10,digits-i);
    }

    //removing any tailing zeros

    while(result%10==0){
        result=result/10;
    }

    return result;


}

int main(){
    int t;
    cin>>t; //number of testcases
    for(int i=0;i<t;i++){
        int a,b,ra,rb,rsum,output;
        cin>>a>>b;  // the two numbers
        ra=rev_num(a);
        rb=rev_num(b);
        rsum=ra+rb;
        output=rev_num(rsum);
        cout<<output<<"\n";
    }
}
  • created

    Jun '20
  • last reply

    Jun '20
  • 4

    replies

  • 545

    views

  • 2

    users

  • 1

    link

Try these:

3
41718316 33681906
93943648 97930632
58252693 73313889

This is the output it gives on ideone.

-1717451438
-1949155638
-2080935338
-2080935338
-2080935338
-2080935338
-2080935338
-2080935338
-2080935338
-2080935338
-2080935338
-2080935338
-2080935338

Sorry typo - that 13 should have been 3 - now edited and corrected.

Apart from that though, can you spot anything wrong with the answers you get? Bearing in mind, you’re adding numbers.

Yes, it is negative. i suppose it is exceeding the limit of int, is it ?
Edit: Just replaced the int with long int, turns out it was exceeding the limit. thanks for your help. <3