Search code examples
c++palindrome

Palindrome program produces incorrect output


I'm trying a problem on SPOJ ("Sphere Online Judge", a programming puzzle site), where I need to generate the smallest palindrome larger than the given number. I tried to solve it by calculating two sides of palindrome with modulo and int division, but it still gives me the wrong answer. What can be the problem?

#include <cmath>
#include <iostream>

using namespace std;

int inverse(int a){
    int inv = 0;
    while( a > 0){
        inv = inv*10 + a%10;
        a = a/10;
    } // while
    return inv;
} // inverse

int main(){
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    for(int i = 0; i < n; i++){
        int a;
        cin >> a;
        int size  = 0;
        int tmp = a;
        while(tmp > 0){
            size++;
            tmp/=10;
        } // while

        bool even = false;
        int middle = size/2;
        if(size%2==0)even = true;
        if(!even)middle++;
        int l = a/pow(10.0,size-middle);
        int r = a%int(pow(10.0,middle));
        int lr = inverse(l);
        if(lr <= r){
            l++;
            lr=inverse(l);
        } // if

        if(!even)
            lr%=int(pow(10.0,middle-1));

        int wynik = l*pow(10.0,size-middle)+lr;

        if(a==9)
            wynik=11;
        else if(a==0)
            wynik = 1;

        cout << wynik << endl;
    } // for

    return 0;
} // main

Solution

  • According to the problem description, you have to be able to handle positive integers of any size less than one million digits. Your implementation is based on the int type, so it can only handle numbers up to around nine digits long (give or take a few digits depending on your system's INT_MAX).

    Sample input:

    1
    100000000000000000000000000000000000000000
    

    Sample output:

    -2147483648
    

    Your output is incorrect. The correct output is 100000000000000000000000000000000000000001.