Hacker News new | ask | show | jobs
by dlcarrier 35 days ago
It's a little awkward, because you'd need to parse the strings in reverse, but if all you need to do is sum, you can do it one digit at a time, while at any given moment only handling only one character from each input string, a carry byte, and one output character.
2 comments

You don't need to parse the strings in reverse. That's for printing integers, not parsing. Roughly:

    int stdin_atoi() {
      int i = 0;
      while (1) {
        int c = getchar();
        if (c >= '0' && c <= '9') {
          i = i * 10 + (c - '0');
        } else { break; }
      }
      return i;
    }
That covers the ‘int’ case, but not the ‘integer’ case described. Unless you have unlimited memory, you’ll need to go least- to most-significant digit; but you’ll need to do that on both inputs, which doesn’t really work with the interface described unless at least the first argument first in memory all at once, so… well, I assume “I under specified this problem and it’s impossible” is the point of this sort of exercise.
That method requires storing an arbitrarily large number, whereas for the least-significant-character-first method, the math itself could be done without using any more data than two input bytes, one of which could double as an output byte, and a carry byte.
How do you know where the first string ends and the second starts? Did you miss the "stdin" part?

This is not

    ./program first_number second_number
Of course the method described requires both input and output buffers, because everything is processed last-character-first.

Now that you mention it, if the assignment had called for arguments, instead of files or pipes, argv points to a writable array, so the result could be written directly to it, negating any need to allocate memory, and any out-of-memory conditions from large input data would occur before the program is even called.

If it usually uses a file to store the numbers, the same could be done by writing the result back to the file, but that only works if it is passed as an argument, as piping it would throw a seek error. I wonder if the instructor would accept an interleaved little-endian input syntax, with a little-endian output; then the program could use pipes without a need to seek. An infinite series of '9' characters would output an '8', followed by one '9' per two input characters.