-3

Hi I ran this code on Codechef's IDE and on Codeblocks. I got answer different answers: 1001 for CODEBLOCK 818(Correct one) Codechef IDE. Please help!.

Code snipplet : http://pastie.org/10223010

#include <iostream>
#include <string>
#include<sstream>
#include<cmath>


using namespace std;
int palin(int n);
int main()
{
    int i,t;
    int n;
    cin>>t;
    for(i=0;i<t;i++){
    cin>>n;
    palin(n);

while(1){
        n++;
    if(palin(n)==1){
        cout<<n<<endl;
        break;
    }

}
    }
    return 0;
}

int palin(int n){
    int len=0;
    int m=0;
    int dum=n;
    while(n!=0){
        n=n/10;
        len++;

    }
    n=dum;

  while(n!=0){
    m=m+((pow(10,(len-1)))*(n%10));
    n=n/10;
    len--;

  }


    if(dum==m)
        return 1;
    else
        return 0;
}

Problem statement :http://www.codechef.com/problems/PALIN/

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

1 Answers1

0

Don't use pow() function as it use float arithmetic and gives wrong answer with integer variables

Instead use custom power function for integer variable, something like

int pw(int a, int b){
    int ans = 1;
    while(b--){
        ans *= a;
    }
    return ans;
}
Sahil
  • 11
  • 3
  • I would be seriously surprised if there wasn't an overload to take care of this for you. Writing a custom function for something this simple is almost never a good idea. Can you catch overflow? are you setting stderr or something like it if it occurs? What about negative exponents? Things like this can really burn you. – Michael Dorgan Jun 10 '15 at 22:47
  • @Sahil Yeah I too feel that you are right , But as Micheal said there should be more feasible approach. – Abhimanyu Shekhawat Jun 11 '15 at 07:04
  • 1
    @MichaelDorgan there is no overloaded function that i know of, see this answer to know why is that so [link](http://stackoverflow.com/a/6621882/4996826) – Sahil Jun 11 '15 at 07:28
  • @Abhimanyu From competition programming point of view there is no need for exception handling, you just have to check corner cases or overflow cases depending on input/output constraints (in your case there is no chance of overflow or underflow). For real-world application you should create proper function with exception handling capabilities or use external libraries. – Sahil Jun 11 '15 at 07:35