logoalt Hacker News

ronsoryesterday at 8:21 PM2 repliesview on HN

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;
    }

Replies

dlcarriertoday at 12:47 AM

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.

addaonyesterday at 9:00 PM

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.