tags:

views:

75

answers:

1

I'm trying to solve the Adding Reversed Numbers problem (ADDREV) at the Sphere Online Judge but my submission keeps coming up wrong answer.

I've tried int, unsigned int, long, and unsigned long for my variables and they all work equally well on my computer with some test data (also below) but they all fail the SPOJ.

I'm hoping someone might be able to shed some insight into why my program would be failing on their system. I've also left a message on their forum but there doesn't seem to be a lot of traffic.

Here's my code:

#include <stdio.h>

#define FIRST 1
#define SECOND 2

int main()
{
    int c, k, x, y, state, place, total, reverse = 0;

    do 
    {
     c = getchar();

     if (c  < 48 || c > 57)
     {
      continue;
     }
     else
     {
      k = k * 10;

      k = k + (c - 48);
     }

    } while (c != '\n');

    state = FIRST;

    place = 1; 

    do 
    {
     c = getchar();

     if (c == ' ')
     {
      state = SECOND;

      place = 1;

      continue;
     }
     else if (c == '\n')
     {
      total = x + y;

      place = 1;

      while ((total / place) >= 10)
      {
       place = place * 10;
      }

      while (place > 0)
      {
       reverse = reverse + ((total % 10) * place);

       total = total / 10;

       place = place / 10;
      }

      printf("%d\n", reverse);

      state = FIRST;

      place = 1;

      reverse = 0;

      x = 0;

      y = 0;

      k--;

      continue;
     }

     if (state == FIRST && (c  >= 48 && c <= 57))
     {
      x = x + ( (c - 48) * place );

      place = place * 10;

     }
     else if (state == SECOND && (c  >= 48 && c <= 57)) 
     {
      y = y + ((c - 48) * place );

      place = place * 10;
     }

    } while (k > 0);

    return 0;
}

And... here's the test data I'm using:

12 
24 1                   
4358 754  
305 794
2762 2563
435 4320
0 0
123 456 
20 20 
10000 10000
999999 999999 
321 583 
9999999 999999

And here's the results my program gives on my computer:

34
1998
1
4236
867
0
579
4
2
8999991
805
89999901

Any help would be appreciated :)

+2  A: 

At this point:

int c, k, x, y, state, place, total, reverse = 0;

you create a variable k but give it no value. Shortly after:

k = k * 10;

you use this variable. At that point, your program exhibits undefined behaviour - anything might happen.

anon
That was it, properly initializing the variables did the trick - thanks! I was under the impression that they would all be initialized to 0 but apparently not.
Fredrick Pennachi
The C Standard says that only static variables are automatically initialised to zero.
anon
The OP might have thought that the `= 0` at the end of the line applied to all the variables declared there, rather than just the last.
caf