Precise C++ 0ms solution

  • 0
    // Forward declaration of the read4 API.
    int read4(char *buf);
    class Solution {
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
        int read(char *buf, int n) {
            int i = 0, ret;
            do {
                ret = read4(buf + i);
                i += ret;
            } while (ret == 4 && i < n);
            return min(i, n);

  • 0

    There is one thing I want to ask. After the do loop, if i>n the characters stored in buf will be more than n. Do we need to make sure that there is only n character in buf? Or to add "if (i > n)buf[n] = '\0';" after the do loop?

  • 0

    Hey nice observation and this is what I had in my mind while writing this: The read4() API always reads chunk of 4 bytes. If n is not multiple of 4 (cases where file is too long and we do partial read), overflowing bytes will always corrupt the memory locations beyond buf limit. This can be done cleanly by having local buffer of 4 bytes passing it to read4(), but it requires additional memcpy().

    Ideally, we can't and shouldn't modify the bytes outside buf. In that sense, my code as well as appending \0 at end, both are bad.

Log in to reply

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