Simple C++ Solution

  • -2
        int read(char *buf, int n) 
            int num = 0, cnt;
            while(num < n && (cnt = read4(buf))) 
                num += cnt;
                buf += cnt;
            if(num >= n) 
                buf[n-num] = '\0';
                num = n;
            return num;

    I feel that it is so simple that I don't need to provide explanation...

  • 0

    Could you explain a little bit?
    As far as I know,

    "num" is the counter to count how many chars in n that has been read;

    "cnt" is the counter that one read4() has been read;

    but what is "but[n-num]" ?

    if num is larger or equal to n, then "n - num" could be 0 or negative, what's the meaning of a negative index of an array?

    and why you return "num"? Is it always same with n?

  • 0

    when num > n; it causes buffer overflow.

  • 0

    many unnecessary loop.Check and think again.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.